This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Java cast to superclass and call overload method
(1 answer)
Closed 5 years ago.
Super keyword related doubt.
class Parent{
int x=40;
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{ int x=20;
void show() //method overriding has been done
{
System.out.println(super.x); // prints parent data member
System.out.println(((Parent)this).x); /*same output as previous statement which means super is similar to (Parent)this*/
System.out.println("child");
super.show(); // invokes parent show() method
((Parent)this).show(); //Doesnt invoke parent show() method.Why?
}
public static void main(String s[])
{
Child c1=new Child(); //Child class object
c1.show();
}}
So, System.out.println(super.x) and System.out.println(((Parent)this).x) prints the same value.So if super.show() calls parent class show() method then why is ((Parent)this).show(); unable to call parent show()? Please tell appropriate explaination for this.
Constructor Chaining
in Java keyword this represent current object and when one class extends another then its super class reference variable may hold child class reference variable that's is in your code is ((Parent)this).x ,
while super keyword is used to call directly super class constructor and its variables.
at the same time when super class variables holds child class object and when we use super it refers same object .
How to call one constructor from another constructor in Java or What
is Constructor Chaining in Java is one of the tricky questions in Java
interviews. Well, you can use this keyword to call one constructor
from another constructor of the same class if you want to call a
constructor from based class or super class then you can use super
keyword. Calling one constructor from other is called Constructor
chaining in Java. Constructors can call each other automatically or
explicitly using this() and super() keywords. this() denotes a
no-argument constructor of the same class and super() denotes a no
argument or default constructor of parent class. Also having multiple
constructors in the same class is known as constructor overloading in
Java.
Read more: http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html#ixzz4bJ5C069o
Calling ((Parent) this).show(); on what is really a Child object causes Child.show() to be called. Whether you are doing it as myObject.show() or through this makes no difference for which version of the method gets called — it’s always the method determined by the object’s runtime type, in this case Child.
So you have a recursive call, leading to infinite recursion.
super.show() on the other hand calls the method in the super class, in this case Parent.
Related
This question already has answers here:
Does a superclass instance also being created when creating a subclass instance?
(4 answers)
Closed 3 years ago.
We have below code:
class Parent {
public int i = 5;
}
class Son extends Parent {
}
public class MyTest {
public static void main(String[] args){
**Son son = new Son();**
System.out.println(son.i);
}
}
When execute Son son = new Son(), below questions confused with me:
Will create Parent instance in memory or not? I know that before create Son instance, will invoke Parent default Constructor with no parameter, is that correct invoking Constructor and create instance are different things?
If did not create Parent instance, but where is field i store in Son instance? Cause we can get value of i via son reference?
Many thanks!!!
Will create Parent instance in memory or not? I know that before create Son instance, will invoke Parent default Constructor with no parameter, is that correct invoking Constructor and create instance are different things?
An instance of Parent will not be created, and indeed, the constructor of Parent will be invoked. Constructors are just special blocks of code for the JVM to run when creating an instance. There's no rule that says, "when creating an instance of T, only the constructor of T can be run".
If did not create Parent instance, but where is field i store in Son instance? Cause we can get value of i via son reference?
Just because it's not written in the source code, doesn't mean it's not there. By writing Son extends Parent, you are telling the compiler and the runtime that (among other things) Son does have a field called i, so you don't have to declare it again in Son. This is one of the main aims of inheritance - reduce duplicate code.
When you create an instance of a subclass, a superclass constructor must be called to initialize the superclass fields, which in this case is son.i. When there is no constructor given for the superclass, Java implicitly creates a default constructor, equivalent to the below code:
public Parent() {}
When Parent is extended, the constructor of Son begins by calling the constructor of Parent, implicitly done via the below code:
public Son() {
super() // Calls Parent()
}
In short, yes. A subclass does generate fields for the superclass in the memory. Think of a subclass as a parent class with a few bells and whistles. For example:
Parent myObj = new Son();
System.out.println(myObj.i); // Still prints 5 because i is still a variable of son
Questions 1: Yes, Java will automatically create a default Parent constructor if you haven't created one already and each time a new Son object is created, the Parent constructor will be called too. You can explicitly call the Parent constructor of your choice (assuming you've defined one or more) by making a call to super(...) in the first line of the Son constructor.
Question 2: The field 'i' is part of the Parent class. The way you've written it at the moment (with public access) it will be accessible to both the Son class and everyone else who wants to change it.
A further comment: It is good programming practice to make fields private to a class and, if possible, final.
///Example code here
Superclass{
method1(){
print(do1);
}
method2(){}
}
Subclass extends Superclass{
///override method1
method1(){
print(do2);
}
method3(){}
}
I have a question for the polymorphism in java, which is when Superclass s =new Subclass(). the "s" object always invoke the method in the Superclass, but when the override method happened, the "s" will point back to the override methods.
Update:
So, the question is who will create a heap address for the reference "s", if it can be compiled and running in the end. If the Superclass created it, why new Subclass() rather than new Superclass(). If the Subclass created it, why cannot use s.method3().
s can call method3. You just have to cast it first. If they allowed s to call method3 as Superclass, it wouldn't make sense because not ALL Superclass can call method3.
Dynamic binding of method will decide at run times , so first when you call method with s as its reference of super class compiler will always first check if superclass has that method or not. there are 2 case
1. If super class has the method JVM will go ahead and check in child class, If child class has overriding method then that method will be called , if child class doesn't have that method than normally parent class method will call.
2. If super class does not have that method , then compilation fails as compiler could not identified any method in class of reference variable
So in your case if super class doesn't have method3 then it will defiantly gives compilation error
I have an abstract class and its concrete subclass, when I create an object of subclass it automatically calls the super constructor. Is the JVM internally creating an object of the abstract class?
public abstract class MyAbstractClass {
public MyAbstractClass() {
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
public static void main(String[] args) {
new ConcreteClass();
}
}
then how constructor exists without an object in JVM ?? (In case of abstract class)
Also constructor gets executed after object is being created then without creating the object of abstract class how the default constructor get executed ?? (This is mentioned in Java Doc)
Is it true that you can't instantiate abstract class?
Yes.
Is JVM internally create object of abstract class ?
No, but it's a common misunderstanding (and that wouldn't be an unreasonable way for it to be done; prototypical languages like JavaScript do it that way).
The JVM creates one object, which is of the class you created (in your case, ConcreteClass). There are aspects of that one object that it gets from its superclass (MyAbstractClass) and from its subclass (ConcreteClass), but there is only one object.
The object is an aggregate of all of its parts, including parts that seem to have the same name, such as a method of the superclass that is overridden by the subclass. In fact, those methods have different fully-qualified names and don't conflict with one another, which is why it's possible to call the superclass's version of an overridden method.
So if it's just one object, why do you see the call to MyAbstractClass's constructor? Before we answer that, I need to mention a couple of things the Java compiler is doing that you don't see in the source code:
It's creating a default constructor for ConcreteClass.
In that constructor, it's calling the MyAbstractClass constructor.
Just to be thorough: In the MyAbstractClass constructor, it's adding a call to the superclass's (Object) constructor, because there's no super(...) call written within the MyAbstractClass constructor.
Here's what the code looks like with the bits the Java compiler adds for you filled in:
public abstract class MyAbstractClass {
public MyAbstractClass() {
super(); // <== The Java compiler adds this call to Object's constructor (#3 in the list above)
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
ConcreteClass() { // <== The Java compiler adds this default constuctor (#1 in the list above)
super(); // <== Which calls the superclass's (MyAbstractClass's) constructor (#2 in the list above)
}
public static void main(String[] args) {
new ConcreteClass();
}
}
Okay, with that out of the way, lets touch on a point TheLostMind very usefully mentioned in a comment: Constructors don't create objects, they initialize them. The JVM creates the object, and then runs as many constructors (they really should be called initializers) against that one object as necessary to give each superclass a chance to initialize its part of the object.
So in that code, what happens (and you can step through this in a debugger to fully understand it) is:
The JVM creates an object
The ConcreteClass constructor is called
The first thing that constructor does is call its superclass's constructor, in this case MyAbstractClass's constructor. (Note that this is an absolute requirement: The Java compiler will not allow you to have any logic in the constructor itself prior to the superclass constructor call.)
The first thing that constructor does is call its superclass's constructor (Object's)
When the Object constructor returns, the remainder of the MyAbstractClass constructor runs
When the MyAbtractClass constructor returns, the remainder of the ConcreteClass constructor runs
The object is returned as the result of the new ConcreteClass() expression.
Note that the above would get more complicated if there were instance fields with initializers. See the JLS and JVM specs for the full details.
JVM doesn't create object of abstract class. it is calling its super constructor
JVM will create one object, an instance of the concrete class which inherits fields and methods of abstract class
I have derived a class in java.
I noticed that the superclass constructor gets called before code in my derived class constructor is executed.
Is there a way to invert that order?
Example:
class Animal
{
public Animal()
{
//do stuff
}
}
class Cat extends Animal
{
int var;
public Cat(int v)
{
var = v;
super();
}
}
This is what I would like to do, but calling super() like that gives an error...
No, there is no way to invert that order. If you explicitly call a parent class constructor you are required to do it at the top of your constructor. Calling it later would allow a child class to access the parent class's data before it's been constructed.
No, you can't invert the order of constructor calls this way. A call to super() must be the first statement in a constructor. And if there is no such call, Java inserts an implicit call to super() as the first statement.
The JLS, Section 8.8.7, states:
The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
ConstructorBody:
{ [ExplicitConstructorInvocation] [BlockStatements] }
There isn't a way to call run the sub class constructor before superclass constructor. That's basically like trying to create the subclass even before the superclass gets created, which is impossible since the subclass relies on superclass attributes to get created.
This question already has answers here:
Why can't this() and super() both be used together in a constructor?
(11 answers)
Closed 5 years ago.
I have this program:
public class A
{
public A(){
System.out.println("I am in A");
}
public static void main(String args[]){
B a = new B("Test");
}
}
class B extends A
{
public B(){
System.out.println("I am in B");
}
public B(String s){
this();
super();
System.out.println("I am in B as " + s);
}
}
Now why can't I call the this constructor of B to invoke the default constructor? This is giving me compile time error.
this and super must be the first line in a constructor.
EDITED:
Language spec
8.8.7. Constructor Body
The first statement of a constructor body may be an explicit
invocation of another constructor of the same class or of the direct
superclass (§8.8.7.1).
this() calls another constructor in the same class.
super() calls a super constructor.If no super() is explicitly written,the compiler will add one implicitly. Hence, you will end up calling super() twice.
So, both are not allowed.
EDIT
In context of your code : remember, super() should always be the first line in a constructor.
Upon further reflection my answer as it was below is basically correct but lacking some nuance. Essentially, you can call a super constructor once. This is to ensure your super class is only constructed once. This means that the first line of a given constructor can be a call to another constructor in the current class or a call to a constructor in the super class. This also means that you can only call another constructor once in any given constructor; you must choose to call one in the current or super class. This ensures that all super classes will be fully constructed before the current object is.
Old explanation:
The fundamental reason is that all super classes must be constructed before the subclass can be. To this end, Java will implicitly call super() if no such invocation exist on the first line of a constructor. The only way to override this behavior is to explicitly call a different constructor in your super class. Basically, Java must create your hierarchy before you can be created.
Putting your constructor first violates this requirement and therefore is illegal.
According to Java this() and super() should be the first statement in constructor.Now the point is we can not write both at once as a first line.If u write this() and not super,dont expect that super will be called implicitly.
It is as simple as it is.U have no option to write them together in single constructor body