Inheriting from inner class - java

public class A {
public A() {
System.out.println("A()");
}
public class B {
public B() {
System.out.println("B()");
}
}
}
class Caller extends A.B {
Caller(A a){
a.super();
}
}
public class Main {
public static void main(String[] args) {
Caller as= new Caller(new A());
}
}
Why do we need a.super() call in class extending inner class? What does it doing?
Without a.super() program does not want to compile.
Error:(48, 20) java: an enclosing instance that contains A.B is required

a.super() does not call the A constructor. The A constructor runs as a result of the expression new A() in Main.main().
The a.super() invokes the nullary (and only) B constructor, specifying a as a reference to the containing instance of A, which, as a subclass of inner class A.B, each Caller must have.

The answer is: because that's how it is specified in the Java Language Specification.
Your class A.B is an inner class of A. The constructor has a hidden argument of type A - the enclosing (outer-class) instance.
You have subclassed A.B in your class Caller, which is itself not an inner class. But the constructor of the superclass needs this hidden instance of A - the outer class instance.
The way in which you pass this in Java is using this a.super(); syntax.
The Java Language specification defines this in section 8.8.7.1:
Qualified superclass constructor invocations begin with a Primary
expression or an ExpressionName. They allow a subclass constructor to
explicitly specify the newly created object's immediately enclosing
instance with respect to the direct superclass (§8.1.3). This may be
necessary when the superclass is an inner class.

Error says it all. One of key thing about inner classes (non-static nested ones) is that they have access to its outer (enclosing) instance. But inner class needs to know to which exactly outer instance it belongs. This information is saved in Outer this$0 reference which is not accessible to us, but it still needs to be set as some point, and that point is code of constructor.
This is why we are creating inner class instances via outer.new Inner() like
Outer outerInstance= new Outer();
Outer.Inner innerInstance = outerInstance.new Outer.Inner();
// ^^^^^^^^^^^^^^^^^
Thanks to that, outer instance is also passed to Inner class constructor (as hidden parameter).
Now since you are extending inner class, it means that your class will simply specify inner class, but it doesn't mean it stop being of Inner type.
So since instance of your Caller is also considered as A.B inner class (since it extends it) you must ensure, that it will have knowledge about its outer instance (of A class). To make this possible you in constructor of our class, you need to
have instance of your class
call constructor of inner superclass A.B, so you would let it save that outer class reference in this$0 variable.
First point is solved by passing A instance as argument of your class constructor Caller(A a).
Second point is done in similar way as calling outerInstance.new Inner(), but this time we can't use new keyword because we don't want to create new object of Inner class. We want to invoke code from superclass constructor to initialize current object (and its hidden this$0 field properly). Usual way to do it is by calling super(). Only thing which could be a bit strange, is that we need to somehow let super() call which outer instance is enclosing one. So probably to make it similar to outer.new Inner() syntax, we are using outer.super() syntax, which in your case is
a.super();

Since your Caller class extends A.B, the first call the Caller constructor makes will be the A.B constructor (even if you don't see it in your code).
So a.super() is NOT calling the A.B constructor.

It's not a.super() calling A.B constructor, but rather Caller() constructor calls it implicitly, since Caller extends A.B. Only after that the a.super() line is executed.

Related

Program initialises both subclas and superclass constructors at once [duplicate]

Consider this code:
class Test {
Test() {
System.out.println("In constructor of Superclass");
}
int adds(int n1, int n2) {
return(n1+n2);
}
void print(int sum) {
System.out.println("the sums are " + sum);
}
}
class Test1 extends Test {
Test1(int n1, int n2) {
System.out.println("In constructor of Subclass");
int sum = this.adds(n1,n2);
this.print(sum);
}
public static void main(String[] args) {
Test1 a=new Test1(13,12);
Test c=new Test1(15,14);
}
}
If we have a constructor in super class, it will be invoked by every object that we construct for the child class (ex. Object a for class Test1 calls Test1(int n1, int n2) and as well as its parent Test()).
Why does this happen?
The output of this program is:
In constructor of Superclass
In constructor of Subclass
the sums are 25
In constructor of Superclass
In constructor of Subclass
the sums are 29
Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.
see 3.4.4 in here
Yes. A superclass must be constructed before a derived class could be constructed too, otherwise some fields that should be available in the derived class could be not initialized.
A little note:
If you have to explicitly call the super class constructor and pass it some parameters:
baseClassConstructor(){
super(someParams);
}
then the super constructor must be the first method call into derived constructor.
For example this won't compile:
baseClassConstructor(){
foo();
super(someParams); // compilation error
}
super() is added in each class constructor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.
Java classes are instantiated in the following order:
(at classload time)
0. initializers for static members and static initializer blocks, in order
of declaration.
(at each new object)
create local variables for constructor arguments
if constructor begins with invocation of another constructor for the
class, evaluate the arguments and recurse to previous step. All steps
are completed for that constructor, including further recursion of
constructor calls, before continuing.
if the superclass hasn't been constructed by the above, construct the
the superclass (using the no-arg constructor if not specified). Like #2,
go through all of these steps for the superclass, including constructing
IT'S superclass, before continuing.
initializers for instance variables and non-static initializer blocks, in
order of declaration.
rest of the constructor.
That´s how Java works. If you create a child object, the super constructor is (implicitly) called.
In simple words if super class has parameterized constructor, you need to explicitly call super(params) in the first line of your child class constructor else implicitly all super class constructors are called untill object class is reachead.
The subclass inherits fields from it's superclass(es) and those fields have to get constructed/initialised (that's the usual purpose of a constructor: init the class members so that the instance works as required. We know that some people but a lot more functionality in those poor constructors...)
Constructor implements logic that makes the object ready to work. Object may hold state in private fields, so only its class' methods can access them. So if you wish instance of your subclass be really ready to work after calling constructor (i.e. all its functionality including inherited from base class is OK) the base class's constructor must be called.
This is why the system works this way.
Automatically the default constructor of base class is called. If you want to change this you have to explicitly call constructor of base class by writing super() in the first line of your subclass' constructor.
The base class constructor will be called before the derived class constructor. This makes sense because it guarantees that the base class is properly constructed when the constructor for the derived class is executed. This allows you to use some of the data from the base class during construction of the derived class.
When we create an object of subclass, it must take into consideration all the member functions and member variables defined in the superclass. A case might arise in which some member variable might be initialized in some of the superclass constructors. Hence when we create a subclass object, all the constructors in the corresponding inheritance tree are called in the top-bottom fashion.
Specifically when a variable is defined as protected it will always be accessible in the subclass irrespective of whether the subclass is in the same package or not. Now from the subclass if we call a superclass function to print the value of this protected variable(which may be initialized in the constructor of the superclass) we must get the correct initialized value.Hence all the superclass constructors are invoked.
Internally Java calls super() in each constructor. So each subclass constructor calls it's superclass constructor using super() and hence they are executed in top-bottom fashion.
Note : Functions can be overridden not the variables.
Since you are inheriting base class properties into derived class, there may be some situations where your derived class constructor requires some of the base class variables to initialize its variables. So first it has to initialize base class variables, and then derived class variables. That's why Java calls first base class constructor, and then derived class constructor.
And also it doesn't make any sens to initialize child class with out initializing parent class.
Constructor of Super class in called first because all the methods in the program firstly present in heap and after compilation they stores in to the stack,due to which super class constructor is called first.
There is a default super() call in your default constructors of sub classes.
//Default constructor of subClass
subClass() {
super();
}
"If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem."
(source: https://docs.oracle.com/javase/tutorial/java/IandI/super.html)
I'll try to answer this from a different perspective.
Suppose Java didn't call the super constructor for you automatically. If you inherit the class, you'd have to either call the super constructor implicitly, or rewrite it yourself. This would require you to have internal knowledge of how the super class works, which is bad. It would also require to to rewrite code, which is also not good.
I agree that calling the super constructor behind the scenes is a little unintuitive. On the other hand, I'm not sure how they could have done this in a more intuitive way.
As we know that member variables(fields)of a class must be initialized before creating an object because these fields represent the state of object. If these fields are explicitely not initilized then compiler implicitely provides them default values by calling no-argument default constructor. Thats why subclass constructor invokes super class no-argument default constructor or implicitely invoked by compiler .Local variables are not provided default values by compiler.
here your extending Test to your test1 class meaning u can access all the methods and variable of test in your test1. keep in note that u can access a class methods or variable only if memory is allocated to it and for that it need some constructor either a default or parameterized ,so here wen the compiler finds that it is extending a class it will try to find the super class constructor so that u can access all its methods.
Parents Exits First!!
And like real world Child Can't exist without the Parents..
So initialising parents(SuperClass) first is important in order to use thrm in the children(Subclass) Classes..

Inner classes inheritance and access to enclosing class methods/fields

Here are two statements I found concerning inner classes
JavaDocs:
As with instance methods and variables, an inner class is associated
with an instance of its enclosing class and has direct access to that
object's methods and fields. Also, because an inner class is
associated with an instance, it cannot define any static members
itself.
On another site I found this:
A nested class, for the most part, is just that—a class declared in
the definition of an enclosing class. It does not inherit anything
from the enclosing class, and an instance of the nested class cannot
be assigned to a variable reference to the enclosing class.
Aren't the bold marked lines contradicting?
How can you not inherit a surrounding objects fields and methods and at the same time have access to its fields and methods?
No, they do not conflict. Look at the following example:
public class A {
public void foo() {
//some code
}
public class B {
public void bar() {
foo();
}
}
}
In this example, the innerclass B can access the method of A (or any of its' fields, actually), but in no way does inheritance takes place.
For instance, the following change to B would result in a compilation error:
public class B {
public void bar() {
super.foo();
}
}
Because B does not inherit from A. It can access its' instance members, but it does not extend (inherit) from it.
Please do not see the terms nested class and inner class as an opposite or something similar. In fact, a nested class simply describes all sorts of classes that are declared inside another class:
Nested classes that are declared static are simply called static nested classes.
Non-static nested classes are called inner classes. There are three types of them (see JLS §8.1.3 for more info):
A non-static member class.
A local class.
An anonymous class.
The first paragraph you quoted explains that an inner class has access (read: access, not inherit) to the methods and fields of the enclosing instance. Note, it is about an instance, not the class.
The second paragraph tries to explain that there is no relationship between a class and a nested class inside it, except for their locations.

Use super() with reference in Java

I have three classes
class WithInner {
class Inner {}
}
public class InheritInner extends WithInner.Inner
{ //constructor
InheritInner(WithInner wi) {
wi.super();
}
}
This example is taken from Eckel's Thinking in Java. I can't understand why we can't call wi = new WithInner(); instead of .super()? And while calling wi.super() we are calling Object's default constructor, aren't we?
Inner classes maintain a reference to an outer instance (the exception is static inner classes). In this case, a WithInner.Inner instance has a reference to the containing WithInner instance. This association is created when the inner class is instantiated.
You cannot create an instance of the inner class without a reference to the outer class. A class that extends such an inner class also has by implication such a reference, and needs to delegate to the inner class constructor in order to set up the association. The syntax for doing that is as shown in your example:
wi.super();
Here, super() essentially refers to the superclass constructor - that is, the WithInner.Inner constructor. The constructor takes no parameters formally, but it still needs a reference to the outer instance (of type WithInner). The line as a whole essentially means "call the superclass constructor, and associate with the wi instance".
Compare to the syntax for instantiation of an inner class with explicit association:
wi.new WithInner.Inner()
Yes, that's also valid syntax. It's not commonly seen in the wild, though (because inner class instances are normally only created from within the outer class anyway, and in that case the association is implicit - there's no need in that case for this syntax, which provides the association explicitly).
With specific reference to your question:
I can't understand why we can't call wi = new WithInner(); instead of .super()?
This would not associate the created WithInner instance with the inner class instance. You'd get a compile-time error because your InheritInner constructor wouldn't any longer be explicitly calling the synthesized superclass constructor, and it can't be called implicitly because it needs the outer instance reference for association. It's probably easiest to think of the outer instance reference as a hidden parameter to the inner class constructor (indeed, that's how it's implemented under the hood).
And while calling wi.super() we are calling Object's default constructor, aren't we?
No, you're calling the WithInner.Inner constructor, which has a "hidden" parameter for the outer instance reference; wi is essentially passed to the WithInner.Inner constructor as a hidden parameter value.

Must Inner classes have a reference to the enclosed class?

I have an inner class (non-static) which is using a reference to an enclosing class in its initialization. Will the inner class keep a reference to the enclosing class now?
class Enclosing {
class Inner {
private final ABC innerField = outerField.computeSomething();
}
private final XYZ outerField = something();
}
UPDATE
I am very much aware that one can reference the outer class with Enclosing.this.
But, if the class doesn't use the reference, must the reference be there after compilation? Is it necessary even if the reference is only used in the initialization?
Where does it say that an inner class always holds a reference to the outer class?
A non-static nested class always holds a reference to the enclosing class. In your example, you can reference the enclosing class from Inner as Enclosing.this.
JLS 8.1.3 "Inner classes and Enclosing Instances":
"An instance i of a direct inner class C of a class O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2)."
Yes. An inner class (or non-static nested class) is just like any other instance member of the outer class, and as such always needs a reference of the enclosing class.
Where does it say that an inner class always holds a reference to the outer class?
In the same place it defines the Outer.this syntax. The existence of this syntax is the existence of the reference. There is nothing to suggest that it is suppressed if not used.
There are two cases of nested-classes:
static nested-classes. The nested-class does not keep reference to the outer-class.
non-static nested-classes. The nested-class does keep a reference to the outer-class.
The case of a static nested-class that extends the outer-class is not as interesting as the
non-static nested-class extending the outer-class.
An important thing to remember is that non static nested classes are simply called inner classes.

How can a Java class have no no-arg constructor?

The Oracle Java tutorial site has this paragraph that is confusing me:
All classes have at least one
constructor. If a class does not
explicitly declare any, the Java
compiler automatically provides a
no-argument constructor, called the
default constructor. This default
constructor calls the class parent's
no-argument constructor, or the Object
constructor if the class has no other
parent. If the parent has no
constructor (Object does have one),
the compiler will reject the program.
If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of? Does it have to do with the constructor being private?
If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of?
I think the basis is of your misunderstanding is that you are thinking that constructors are inherited. In fact, constructors are NOT inherited in Java. So consider the following example:
public class A {
public A(int i) { super(); ... }
}
public class B extends A {
public B() { super(); ... }
}
The class A:
does not inherit any constructors from Object,
does not explicitly declare a no-args constructor (i.e. public A() {...}), and
does not have a default constructor (since it does declare another constructor).
Hence, it has one and only one constructor: public A(int).
The call to super() in the B class tries to use a non-existent no-args constructor in A and gives a compilation error. To fix this, you either need to change the B constructor to use the A(int) constructor, or declare an explicit no-args constructor in A.
(Incidentally, it is not necessary for a constructor to explicitly call a superclass constructor ... as I've done. But a lot of people think it is good style to include an explicit call. If you leave it out, the Java compiler inserts an implicit call to the superclasses no-args constructor ... and that results in a compilation error if the no-args constructor does not exist or is not visible to the subclass.)
Does it have to do with the constructor being private?
Not directly. However, declaring a constructor private will prevent that constructor being called from a child class.
The key thing to understand is that the no-arg constructor will only be automatically generated if the class doesn't already have a constructor.
It's thus easy to create a class that doesn't have a no-arg constructor.
The simplest way to think of this problem is as follows:
The non-args constructor is provided as the default constructor by Java for any class you create.
The moment you create a custom constructor with arguments, Java says “hey, this class has got a custom constructor, so I am not going to bother creating/supplying the default non-args constructor!”
As a result now your class does NOT has the default non-args constructor.
This means when you create a subclass, based on your class, you need explicitly call the arguments based custom constructor that you created.
If you have a sub-class of a sub-class
class A
{
A(int i) {..}
}
class B extends A
{
}
Here the default constructor inserted into B will try to invoke A's no-argument constructor (which doesn't exist) as it only has a constructor taking one argument
The immediate superclass of the object must have a protected or public constructor (or no constructor at all, in which case one will be created). So, if I create a class that extends Object, with a private constructor only, then nothing will be able to extend my class.
Yes. A private contructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
The declaration of a private constructor prevents the automatic generation of a default constructor.
EDIT:
A class defined within another class
is called a nested class. Like other
members of a class, a nested class can
be declared static or not. A
nonstatic nested class is called an
inner class. An instance of an inner
class can exist only within an
instance of its enclosing class and
has access to its enclosing class's
members even if they are declared
private.
What this means is that if you inherit from a line of class(es) that make the default no-arg constructor private (or it does not exist, for example), your sub-classes must declare a constructor in line with its parent's alternative constructor.
For example, the following declaration of Bar is not allowed:
public class Foo {
private Foo() { } // or this doesn't even exist
public Foo(int i) {
}
}
public class Bar extends Foo {
}
Let me append to all aforementioned one more interesting case where the default/no-arg constructor is infeasible, in the sense that unless it is explicitly declared, the compiler cannot assume it and yet it has nothing to do with subclassing. This is the case of having a class with a final field which expects a constructor to initialize it. For example:
class Foo extends Object {
private final Object o;
public Foo(Object o){
this.o = o;
}
}
Here it's easy to see that an instantiation of a Foo-object requires the initialization of the final field o so any invocation of Foo() - directly or not - is doomed to failure... Let me underline that the no-arg constructor in the super class (Object) exists and is publicly accessible but it is the presence of the final field (o) that deactivates it in Foo.

Categories