Reputation: 33
I'm trying to learn java oop and i find some problem understanding the use of super method when i make some exemple . Please chek the code below .
can you please tell me why the super(); method doesn't refer to the superClass ? i don't understand .
superClass :
package javaapplication;
public class A {
protected String val;
public A(){
this.val = " Class A ";
}
}
subClass
package javaapplication;
public class B extends A {
public B(){
this.val = " Class B";
System.out.println(super.val);
}
}
Main Class
package javaapplication;
public class JavaApplication {
public static void main(String[] args) {
B a = new B();
}
}
output : run : Class B
why i got "Class B" ?
Upvotes: 0
Views: 575
Reputation: 34424
when you doB a = new B();
constructor of B is executed which internally call base class constructor as the first operation.So this sets the value of variable val as Class A
. But then you are manually doing this.val = Class B
which sets the value again as Class B
Just comment out this.val = Class B
from constructor B, it will print Class A
Upvotes: 1
Reputation: 1626
A constructor in Java (now focus on your constructor of class B) ALWAYS calls either another constructor of class B if you explicitly tell you to do so with this(arguments...)
or a constructor of the super class A if you explicitly tell you to do so with super(arguments...)
or if you don't specify any call to another constructor it calls super()
. And this call is the first instruction of any constructor. Unless the class you are talking about is Object.
So first the A constructor is called, setting val to "Class A" but then the constructor of class B continuous erasing that value and replacing it with "Class B".
Albeit a good example on how constructors work but in essence bad programming as this is not what you would do. A good programmer would add a contstructor in class A accepting the value for val and in class B you would call it using super("Class B") and val would be a private variable defined in class A.
Note that because class B extends class A, any instance of class B has the attributes defined in class B and class A, so super.val or this.val is doing referencing exactly the same variable. One could add a new variable val in class B but again this would be bad programming, if the compiler would accept this, I am not sure.
Upvotes: 1
Reputation: 8446
Because there is only one val
variable, and your B
constructor is setting it to " Class B".
You can use super.something
to refer to something
(member variable or method) on the superclass instead of the current class, but those will only be different if both classes declare something
. In this case, both A
and B
are sharing the val
defined by A
.
Upvotes: 7