filmov
tv
Java 24 | super keyword in java | invoking super class constructor

Показать описание
It is used to differentiate the members of superclass from the members of subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.
class Parent {
String name;
}
class Child extends Parent{
String name;
void set_names()
{ name ="child";
}
void print_names()
}
public static void main(String args[]) {
Child obj = new Child();
}
}
Output:-
child parent
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass.
But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.
super(values);
class Superclass {
int age;
Superclass(int a) {
age = a;
}
public void getAge() {
}
}
public class Subclass extends Superclass {
Subclass(int x) {
super(x);
}
public static void main(String args[ ]) {
Subclass s = new Subclass(22);
}
}
Output :- The age is: 22
It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.
class Parent {
String name;
}
class Child extends Parent{
String name;
void set_names()
{ name ="child";
}
void print_names()
}
public static void main(String args[]) {
Child obj = new Child();
}
}
Output:-
child parent
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass.
But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.
super(values);
class Superclass {
int age;
Superclass(int a) {
age = a;
}
public void getAge() {
}
}
public class Subclass extends Superclass {
Subclass(int x) {
super(x);
}
public static void main(String args[ ]) {
Subclass s = new Subclass(22);
}
}
Output :- The age is: 22