Why does nesting a class give the containing class access to the child class' protected data? - class

The question may be a bit confusing, and is best illustrated by an example:
unit Test
interface
type
TestClass = class()
Splitter1: TcxSplitter;
procedure SomeMethod();
end;
implementation
uses
cxSplitter;
// Locally-declared child type
type
TcxSplitterAccess = class(TcxSplitter);
procedure TestClass.SomeMethod()
var
pos: integer;
begin
// Access to protected field FPositionBeforeClose by casting
pos := TcxSplitterAccess(Splitter1).FPositionBeforeClose;
end;
Notice in the implementation section that there is a type TcxSplitterAccess being declared as a child of the TcxSplitter class. In the method SomeMethod(), belonging to the class TestClass, a TcxSplitter object is cast to the locally-declared TcxSplitterAccess class, and then a protected field is accessed on that object.
This is surprising to me as someone coming from a background of languages like Java, C++, C#, etc. In those languages, it is possible to access protected data in an object so long as you are doing it from within that object's type or an inherited type. For example, a method inside of a class ClazzA can access the private fields of other ClazzA objects since access is enforced at the type level rather than the instance level. Declaring a class locally in these languages would not give the containing class access to the local class' protected data (edit: As pointed out in the comments, this is actually not true at least for Java).
In this example, however, the type TestClass is directly accessing a protected field on the TcxSplitter object by first casting to the TcxSplitterAccess type. I am having trouble finding documentation on why this "trick" works. Does Delphi handle access levels fundamentally differently to Java-like languages and allows this sort of thing? Regardless, why does this trick work?
While I stumbled onto this behavior by using a nested, inherited class in order to access fields on the parent class (which breaks encapsulation, and I shouldn't do), the use of inheritance here is unnecessary. If the nested class did not inherit from a class, but instead had its own protected fields defined, TestClass would still be able to access those protected fields.

A unit has implicit-friendship semantics within itself. Types declared in the same unit are "friends" of each other (similar to friend in C++), and so can access each other's private and protected members (but not strict private or strict protected members).
So, in this case:
TcxSplitterAccess derives from TcxSplitter, so TcxSplitterAccess inherits all of the protected (but not private) members of TcxSplitter via normal class inheritance.
TestClass is declared in the same unit as TcxSplitterAccess, so TestClass has access to all of the protected members of TcxSplitterAccess, including the protected members of TcxSplitter (and the protected members of its ancestors).
FPositionBeforeClose is protected in TcxSplitter.
So, that is why TestClass.SomeMethod() is able to access FPositionBeforeClose when type-casting the Splitter1 object to TcxSplitterAccess.
This is covered by the Delphi documentation:
Private, Protected, Public, and Published Declarations
Classes and Objects (Delphi): Visibility of Class Members

Related

In delphi what is the status/scope of a method declared before the private/public/protected keywords

In delphi what is the status/scope of a method declared before the private/public/protected keywords. see below
type
TMyForm = class(TForm)
Procedure test();
private
...
public
...
protected
...
end;
Every time you have a question about the Delphi language or RTL, you should consult the official documentation. In this case, the section named Visibility of Class Members on Classes and Objects contains the following information:
Members at the beginning of a class declaration that do not have a specified visibility are by default published, provided the class is compiled in the {$M+} state or is derived from a class compiled in the {$M+} state; otherwise, such members are public.
So, for instance, in a class derived directly from TObject, any such members are public. In a class derived from TPersistent, which includes all components (and therefore all controls), they are published.

how scala treat companion object?

I'm new to Scala with Java background.
In java when we want to share any field among different objects of class. we declare that field static.
class Car {
static NO_Of_TYRES = 4;
// some implementation.
public int getCarNoOftyres(){
NO_Of_TYRES; // although it's not a good practice to use static without class name
//but we can directly access static member in same class .
}
}
But in Scala we cannot declare static fields in class, we need to use object(companion object) for that.
In scala we will do like this,
class Car {
println(NO_Of_TYRES); // scala doesn't let us do that. gives error
println(Car.NO_Of_TYRES);// this is correct way.
}
object Car {
val NO_Of_TYRES: Int = 4;
}
I'm just curious, how scala treat companion objects?
what different these two key-words (class and object) makes ?
why does scala not letting us access NO_Of_TYRES directly in class?
Companion objects are singleton class instances (and definitions), just to recall singleton in java is more or less:
class Foo {
private Foo() { }
/* boilerplate to prevent cloning */
private static Foo instance = new Foo();
public static Foo getInstance() { return instance; }
public int bar() { return 5; }
}
and then to call method bar of this object:
Foo.getInstance().bar();
Scala removed all this boilerplate and lets you create equivalent thing with just
object Foo {
def bar: Int = 5
}
and to call it you only need
Foo.bar
now what's the difference between 'object' and 'companion object'? It's actually quite simple - companion object (so the object defined in the same file as a class and having the same name) has access to it's related class private fields and methods, and that's probably why scala authors decided that it should reside in the same file - so that references to private fields are in the same file as their declarations (which I think is always the case both in Java and Scala, unless using reflection magic)
I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods?
See also Section 4.3 of Odersky's book Programming in Scala - Chapter 4 - Classes and Objects
Scala treats everything as pure objects with their instances. In this view a java static member is not part of any instance, it lives a separate and different life.
With the tricks of the keyword object and some syntactic sugar, you can achieve the same result but maintaining the stated principle: a single instance of that object is instantiated and a global access point for the instance is provided.
Scala, as you pointed out, cannot have static variables or methods, as known in Java. Instead, there are singleton objects, which are declared with the keyword object. Calling a method in this objects is like calling a static method in Java, except you are calling the method on a singleton object instead.
If this object has the same name of a class or trait, it is called the companion object of the class/trait. A companion object must be defined inside the same source file as the class/trait. A companion object differs from other objects as it has access rights to the related class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
Companion objects provide us with a means to associate functionality with a class without associating it with any instance of that class. They are commonly used to provide additional constructors

Access specifiers- private vs protected

Are there any risks involved with using the protected member access specifier instead of the private member access specifier?
You have not specified which lamguage but, I assume in OO language like java, a protected member is "visible" to child classes. Latter can use them and may break if you happen to change protected members later due to evolution of your class or change in requirements. No such risk in case of private members. A child class can extend the protected members and make it exposed to the outside (public) world.
This answer assumes you are using a language like java:
private members can only be seen by its own class (and inner classes). This is the safest field visibility since it is hidden from all outsiders. Since it's completely hidden, you are free to change the implementation details or even get rid of the field completely later on.
protected members can not only be seen by all subclasses but also from ALL classes that are in the same package. This makes it much harder to later change the field because more classes might be referencing it.

Injecting with Gin into instance created by GWT.create

I have a custom deferred binder (rebind implementation) that instantiates objects. I would like to have some dependencies (#Inject annotated setter methods) within the instance returned by GWT.create() fulfilled by GIN. Is this possible?
So, given code such as:
Foo foo = GWT.create(Foo.class);
if foo's final implementation has:
#Inject
public void setBar(Bar bar) {
...
}
how do I get bar injected into the returned foo instance automatically by GIN?
Your Ginjector can have methods added to it for the purpose of injecting objects created in some other way. These must take one argument, and should specify the most specific type possible. For example, if MyViewImpl extends BaseView, and both types have dependencies to inject, but you declare
void injectBaseView(BaseView view);
in your ginjector, only the fields/setters declared on BaseView will be dealt with.
EDIT: Also, if no binding is declared, GWT.create will be used to create an instance, so you can have your cake and eat it to. One exception to that as far as I can recall, is when you want to GWT.create one type, but return another (see RPC interfaces for an example).

Calling a protected static Java method from Scala

I have a library here with some Java classes. One class has some protected static methods, which I realize is sorta an OOP no-no but I can't change its code. Assuming I have a Scala class that subclasses the aforementioned Java class, how can I call its protected static members?
See Frequently Asked Questions - Java Interoperability:
This is a known limitation of Scala:
there is no notion of 'static' members
in Scala. Instead, Scala treats
static members of class Y as members
of the singleton object Y (the
companion object of class Y). When
inheriting from this class, one can
access only protected members of class
Y but cannot access protected members
of object Y.
There's no way Scala can simulate
static protected without impairing the
integrity of Scala's object model in a
fundamental way, so this is not going
to change. To work around this
limitation, one has to create an
implementation of the enclosing class
with Java code which encapsulates all
accesses to the protected static inner
class.
See ticket #1806 for more
information and a concrete example of
the limitation and its workaround.