Use of super keyword in Java - java

I have doubt regarding printing of superclass constructor statement even when I have not used super() keyword in subclass.
class A
{
int i;
A()
{
System.out.println("A's constructor");
}
}
class B extends A
{
int i;
B(int a , int b)
{
super.i=a;
i=b;
}
void show()
{
System.out.println(super.i);
System.out.println(i);
}
}
class UseSuper
{
public static void main(String[] args)
{
B b=new B(1,2);
b.show();
}
}
The output of my program is:
A's constructor
1
2
I am unable to understand why I am getting A's constructor printed on my console?

Check the following lines from https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Note: 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.
If a subclass constructor invokes a constructor of its superclass,
either explicitly or implicitly, you might think that there will be a
whole chain of constructors called, all the way back to the
constructor of Object. In fact, this is the case. It is called
constructor chaining, and you need to be aware of it when there is a
long line of class descent.
I hope, it clears your doubts.
[Update]
Posting this update to clear OP's doubts he has mentioned in his comment below.
The following code won't compile because implicit super constructor A() has not been defined and we have also not defined it explicitly. Note that the implicit super constructor A() is automatically defined when there is no other constructor with arguments have been defined.
class A {
int i;
A(int x,int y){
}
}
class B extends A {
int i;
B(int a, int b) {
super.i = a;
i = b;
}
void show() {
System.out.println(super.i);
System.out.println(i);
}
}
public class UseSuper {
public static void main(String[] args) {
B b = new B(1, 2);
b.show();
}
}
[Another Update]
Posting this update to clear OP's another doubt which he has mentioned in his comment below.
The following code too won't compile because the super constructor A() has been declared as private preventing the child class constructor to call it.
class A {
int i;
private A() {
System.out.println("A's constructor");
}
}
class B extends A {
int i;
B(int a, int b) {
super.i = a;
i = b;
}
void show() {
System.out.println(super.i);
System.out.println(i);
}
}
class UseSuper {
public static void main(String[] args) {
B b = new B(1, 2);
b.show();
}
}

When a class extends another class, it is crucial to first call the constructor of the parent class and initialize it, before calling the constructor of the current class.
Even when not visually calling super() in any part of your constructor, Java itself calls the constructor of class A.

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 superclass 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.
In other words, constructor B(int a , int b) calls constructor A() implicitly. In IDE, just change A() to A(int i) and you'll see an error message for constructor B(int a , int b) like "Implicit super constructor A() is undefined. Must explicitly invoke another constructor".

Related

Creating same method in both Parent and Child class provides some weird output

In the below code , I have three questions. I know that having same function in both Parent and Child class does not make any sense and not at all a good design. But , since Java is allowing me to do this , it was possible to write the below code. Trying to understand what actually happens under the hood.
1.When I call f() from the constructor of class A I found that it is calling the child class f(). This is an expected behaviour. But , when the parent constructor calls the overloaded f() before initialising the child class members ,why “B” is getting printed.
2.Why I have two values for a final variable X (x=null , x=B)?.
class A{
A(){
System.out.println("A's Constructor");
f();
}
void f() {System.out.println("A");}
}
class B extends A{
B(){
System.out.println("B's Constructor");
f();
}
final String x = "B";
void f() {System.out.println(x);}
}
public class JavaPOCSamples {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Java POC");
new B();
}
}
Output as below when “B”.trim() is used in the above code:
A's Constructor
null // Note that a final variable X is null
B's Constructor
B // Note that a final variable X is changed to "B"
It is exactly the expected behaviour and is exactly why you should never call overridable methods from a constructor.
The constructor of B first calls the constructor of A, that calls f(), (from class B because it's overridden), that prints x, which is still null. Then B sets it's initialized member variables (so x is no longer null), prints something and calls f() again...
That's is because of the Java Language Specification of Inheritance. Here is a quote from Oracle Java docs.
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
Note: 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.
Small & Simple Explanation:
super() means the constructor (equivalent) of immediate parent class.
class A{
A(){
System.out.println("A's Constructor");
f();
}
// overloaded constructor
// calling super(int a) in child class will call this
A(int a){
System.out.println("A's Constructor " + a);
f();
}
void f() {System.out.println("A");}
}
Specs means, in an inheritance, when an object of the Child Class is created/instantiated, the Object of the Parent Class must instantiate first. So by default super() is invoked always even if you don't invoke it explicitly (any of the overloaded super(arg...) method) in your code.
If you call an overloaded super(args...) of your parent class from your child class, then the default super() is not called.
That means, in your code, Java Compiler puts the default line of super() at very first line in the child constructor, when you don't invoke any of super constructors.
Practical Proof ?? (in your code..??)
class A{
A(){
System.out.println("A's Constructor");
f();
}
// overloaded constructor
// calling super(int a) in child class will call this
A(int a){
System.out.println("A's Constructor " + a);
f();
}
void f() {System.out.println("A");}
}
class B extends A{
B(){
// super(); java adds this line when you don't put any super(args...) call
System.out.println("B's Constructor");
f();
}
B(int a){
super(a);
System.out.println("B's Constructor "+ a);
f();
}
final String x = "B".trim();
void f() {System.out.println(x);}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Java POC");
new B(5);
}
}
Output: (Read comments for some hints..)
A's Constructor 5
null
B's Constructor 5
B
try to play with super() calls.. and get more questions to learn Java deeper. :)
Cheers!!
Recommended reads...
https://stackoverflow.com/a/3767389/6446770
https://stackoverflow.com/a/3767391/6446770
https://stackoverflow.com/a/3767421/6446770

error while creating the Parent object inside child class

I have two class :-
import java.lang.*;
class A {
public A(int number) {
System.out.println("HI I AM INSIDE PARENT CONSTRUCTOR");
}
}
class B extends A {
public static void main(String[] args) {
A obj = new A(10);
}
}
Error:- Implicit super constructor A() is undefined for default constructor. Must define an explicit constructor.
The problem is that you have no constructor declared in B, so the compiler is supplying the default constructor, which in effect looks like this:
B() {
super();
}
Since A has no constructor accepting zero parameters, B can't be compiled. You'll need to add a constructor to B that calls super(int), or you'll need to add a zero-parameters constructor to A.
Principle
A subclass constructor has to invoke the parent constructor.
By default, a no arg constructor is generated by the compiler if you don't declare one.
Important detail : this generated constructor invokes the parent constructor with a no arg invocation.
Your case
You don't declare a constructor in B.
So a default no arg constructor of B is generated :
This constructor is :
B(){
super();
}
but it cannot invoke the parent constructor as it declares one parameter :
public A(int number)
So the compiler emits this error :
Implicit super constructor A() is undefined for default constructor.
Must define an explicit constructor.
To solve your problem, declare a constructor in the subclass that invokes explicitly the parent constructor with the expected argument :
public B(int number) {
super(number);
}
I think you're missing the default constructor in your A class.
See this answer for further explanation.
You have given your own constructor for A having arguments of int. now you need to add a constructor on your own to the class B as well.
public B(int number) {
super(number);
}
When you don't define a constructor in Java, you get an implicit default constructor. When you define a constructor, then the default constructor is not there anymore. So, when you have something like:
Class A {
}
this is equivalent to:
Class A {
A() {
super();
}
}
In your case, class B is calling the default constructor of A, but because A already defined another constructor, the default constructor is then not there anymore, unless you define it explicitly.
Add constructor B(int):
import java.lang.*;
class A {
public A(int number) {
System.out.println("HI I AM INSIDE PARENT CONSTRUCTOR");
}
}
class B extends A {
public B(int number) {
super(number);
}
public static void main(String[] args) {
A obj = new A(10);
}
}
Add:
public B(int number) {
super(number);
}
Cause you have defined a constructor with arguments in parent class,so the compiler won't call the default constructor without arguments.In order to instance parent class before subclass initializing,you have to call parent's explicit constructor in subclass.

Constructor of a derived class (Java)

I'm very new in Java, and about to ask a fundamental question. Hope you guys could help me. Supposed I have a base classe Super and a derived class Sub, which inheritances from class Super as follows:
public class TestSuperSub {
public static void main(String[] args) {
Super ou = new Sub(5,10);
}
}
class Super {
Super() {
System.out.println("Super()");
}
Super(int x, int y) {
System.out.println("Super(int, int)");
}
}
class Sub extends Super {
public Sub(int x, int y) {
System.out.println("Sub(int, int)");
}
}
The output is
Super()
Sub(int, int)
I understand, that ou calls Sub::Sub(int,int) and therefore, Sub(int, int) is printed. But why is Super() printed, since Super::Super() hasn't never been called?
Could someone please explain it to me.
Thanks a lot!
Cheers
By default, Java will call the no-arg constructor of a super class unless you explicitly call another constructor. If you want to call Super(int, int), you must call it explicitly:
public Sub(int x, int y) {
super(x, y);
System.out.println("Sub(int, int)");
}
But why is Super() printed, since Super::Super() hasn't never been called?
It has, because your Sub constructor is implicitly calling it. It's as if you'd written:
public Sub(int x, int y) {
super();
System.out.println("Sub(int, int)");
}
From section 8.8.7 of the JLS:
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).
...
It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
If you want to call a different superclass constructor, you need to do that implicitly. When you call a subclass constructor, that will always work its way up through the inheritance hierarchy, executing the body of the superclass constructor before the subclass constructor... indeed, even field initializers in the subclass are only run after the superclass constructor.
Its the very basic fundamental concept in Java. Its the magic of super keyword and constructor chaining.
Go through these links. Hope this would help you understand the concept.
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_04.htm
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
By Default in constructor of sub class
the first line is call base class default constructor (implicitly) if no constructor is mentioned that is **
super();
**
if you write
super(x,y);
then other constructor will be called
Note : First line of constructor is to call base class constructor.
if there is no super class then Object class's constructor is called
When you instantiate a class, all the superclass hierarchy must also be instantiated and it will be done so through the null constructors automatically available for each class.
The following code
public class Superclassing {
public static void main(String[] args) {
new C();
}
Superclassing() { System.out.println("super"); }
}
class A extends Superclassing {
A() { System.out.println("A"); }
}
class B extends A {
B() { System.out.println("B"); }
}
class C extends B {
C() { System.out.println("C"); }
}
outputs
super
A
B
C
It is done so by design as mentioned in Skeet's answer and also here (oddly, it is mentioned before it is explained in 8.8.7):
JLS 8.8.3. Constructor Modifiers
The lack of native constructors is an arbitrary language design choice
that makes it easy for an implementation of the Java Virtual Machine
to verify that superclass constructors are always properly invoked
during object creation.
(emphasis mine.)
class A{
A(){
System.out.println("no-arg constructor in A");
}
A(int a){
System.out.println("parameterized constructor in A");
}
}
class B extends A{
B(){
System.out.println("no-arg constructor in B");
}
B(int b){
//by default during compilation super() keyword will be added in first line of this constructor
System.out.println("paramterized constructor in B");
}
}
public class TestDemo {
public static void main(String[] args) {
B aVar = new B(10);
aVar = new B();
}
}
Output:
// output for first object i.e, new B(10)
no-arg constructor in A
paramterized constructor in B
//output for second object i.e, new B()
no-arg constructor in A
no-arg constructor in B
A super() keyword will be add by default by the compiler during compilation depending on the Object that u create in main method.

constructors in java

public class A {
public A() {
System.out.println("a1");
}
public A(int x) {
System.out.println("a2");
}}
public class B extends A {
public B() {
super(5);
System.out.println("b1");
}
public B(int x) {
this();
System.out.println("b2");
}
public B(int x, int y) {
super(x);
System.out.println("b3");
}}
I don't understand why the default constructure of A is not applied when I run B b= new B();
B extends A, so First we call the constrcture of A that supposed to print "a1", and then we call the the second constructure of A which prints "a2" and B() prints "b1", but when I run it, it prints only "a2,b1", so obviously A() wan't applied at the beginning- why?
When you say B b = new B(); you are calling the default constructor which is
public B() {
super(5);
System.out.println("b1");
}
Since this already has a call to its super constructor [super(5)] so the compiler will not insert the implicit default constructor. Hence the result.
NOTE: From your question, it seems that you have the idea that all the constructors are called when you create an object. I am afraid that is incorrect. Only that constructor will be called which you explicitly call to create the object. And if that constructor calls other constructor via the this() method, only then the other constructors will be called.
B extends A, so First we call the constrcture of A that supposed to print "a1"
This statement is incorrect.
In class B your no arguments constructor
public B() {
super(5);
System.out.println("b1");
}
calls the constructor of the superclass (class A) which takes an int parameter.
public A(int x) {
System.out.println("a2");
}
You never make a call to super() so the constructor that prints "a1" will not be called when you call any of B's constructors
Calling a super constructor must be the first line of a constructor. If you wish to call the no argument constructor of a superclass (in this case, the one that prints "a1"), you would write...
public B() {
super();
System.out.println("b1");
}
If you do not specify calling a super constructor, then java will automatically put in a call to the no argument super constructor.
That's because you call super(5) in B constructor which call the second A constructor instead of the first one.
I think you missunderstand how Java handles constructors. First of all, by default Java will call only one constructor per class, unless you explicitly tell it to call more using this(...). Secondly, that one construct that is called is the default constructor of the super class (so it will call super(), not this()); so class A actually looks like this:
public class A {
public A() {
super(); // implicit call to super(), which is Object()
System.out.println("a1");
}
public A(int x) {
super(); // implicit call to super(), which is Object()
System.out.println("a2");
}
}
So invoking A() will implicitly call Object(), however invoking A(int x) will also implicitly call Object(), and not - how you seem to assume - A().
Since in B you always explicitly specify to call another constructor, the compiler will not add anything. Below I added comments on what will happen on the calls to super(...) and this(...)
public class B extends A {
public B() {
super(5); // explicit call to A(5), no implict call to A()
System.out.println("b1");
}
public B(int x) {
this(); // explicit call to B(), no implicit call to A()
System.out.println("b2");
}
public B(int x, int y) {
super(x); // explict call to A(x), no implicit call to A()
System.out.println("b3");
}
}
So again, the important thing to remember is that Java will insert a call to super() in the first line of any constructor, unless you explicitly invoke another constructor using this(...) or super(...). It will never insert this() by itself.

super() in Java

Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
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.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff

Categories

Resources