Let’s Do It PL

What is “Inheritance”?

Object-Oriented Programming is built on 4 big principles and one of them is Inheritance. Thanks to this mechanism, developers can easily create objects that have a relationship between them. Also, Inheritance is a very important key to understand other principles.

public class Parrot extends Bird{
}

IS-A Relationship

public class Bird {    String color;    public void fly(){
System.out.println("Bird is flying in the sky freely");
}
public void tweet(){
System.out.println("tweet");
}
}
public class Parrot extends Bird{

public void talk(String word){
System.out.println(word);
}
}
public static void main(String[] args) {
Parrot parrot = new Parrot();
parrot.fly();

//Output: Bird is flying in the sky freely
}

Superclass and Subclass

public class Bird {

public Bird() {
System.out.println("This is a bird");
}

public Bird(String color){
System.out.println("This is a " + color + " bird");
}
}
public class Parrot extends Bird{

public Parrot(String color){
super(color);
}
}
Parrot parrot = new Parrot("yellow");//Output: This is a yellow bird

Private Fields and Final Class

final class Bird {

}

public class Parrot extends Bird{ //compiler error shows this line

}

Inheritance Types

1-Single Inheritance

Example Schema of Single Inheritance
Example Schema of Single Inheritance
Example Schema of Single Inheritance

2-Multilevel Inheritance

Example Schema of Multilevel Inherştance
Example Schema of Multilevel Inherştance
Example Schema of Multilevel Inheritance
public class Animal{    
}

public class Bird extends Animal{
}

public class Parrot extends Bird{
}

3-Hierarchical Inheritance

Example Schema of Hierarchical Inheritance
Example Schema of Hierarchical Inheritance
Example Schema of Hierarchical Inheritance
public class Bird{
}

public class Parrot extends Bird{
}

public class Sparrow extends Bird{
}

4-Multiple Inheritance

Example Schema of Multiple Inheritance

“instanceof” keyword

System.out.println(parrot instanceof Bird);
//Output: true

Summary

Passionate with coding, In love with learning, ambitious to implementing them to his life.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store