Single Inheritance
Implicitly every class inherits the java.lang.object class.
Multilevel Inheritance
In this we have a parent class and child class extending parent class.
while creating object for child class using that object we can call the parent class methods.
If we create a object for child class and object address is same for parent class and child class.
Hierarchical inheritance
A vehicle class has a fuel method a bus and car class extend vehicle class.
Method Overriding
The fuel method return diesal for bus and petrol for car this is method overriding. Still the method name and signature is same.
Class Vehicle{
public String fuel(){
return "null";
}
}
Class bike extends Vehicle{
@override
public String fuel(){
return "petrol";
}
}
class bus extends Vehicle{
@override
public String fuel(){
return "diesal";
}
}
class Main{
public static void main(String[] args){
Bike b = new Bike();
System.out.println(b.fuel());
Bus b1 = new Bus();
System.out.println(b1.fuel());
}
}
Super keyword
Super keyword is used to point out parent class.
public class Parent {
void f1() {
System.out.println("inside parent f1");
}
}
public class Child extends Parent{
void f1() {
super.f1();
System.out.println("inside child f1");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
c.f1();
}
}
Constructor Chaining
Is a feature we can access parent and child constructor in single object creation.
public class SuperClass {
int x;
public SuperClass() {
System.out.println("No args constructor");
}
public SuperClass(int x) {
this();
this.x = x;
System.out.println("All args Constructor");
}
}
public class ChildClass extends SuperClass{
ChildClass(){
this(10);
System.out.println("No args child class constrctor");
}
ChildClass(int x){
super(x);
System.out.println("No args child class constrctor");
}
public static void main(String[] args) {
ChildClass c = new ChildClass();
}
}
Top comments (0)