Home / java / Java Inheritance Best Explanation

Java Inheritance Best Explanation

Inheritance: Acquiring the parent properties in child class

Types of inheritance :

Single :
Class A extends B

multilevel
Class A extends B
Class C extends B

multiple
Class C extends A, B
java won’t support multiple Inheritance

hierarchi
Class B extends A
Class C extends A

Best Example :

Parent.java

public class Parent {
	
  private String output = "hallo";

  protected void setOutput(String output) {
    this.output = output;
  }

  public void print() {
    System.out.println(output );
  }
}

Child.java

public class Child extends Parent {
	public static void main(String args[]){
		Parent c = new Child();
		c.setOutput("child1");
		c.print();
	}
	/*public Child() {
		setOutput("child");
	}*/
}

Superclass reference childclass object

A -> B -> C

A a = new B();
B b = new C();
C c = new A(); // wrong

class A extends Object { }

Object class is super class for every class

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

Object Creation in Java

1)How many ways are there to create an object? 1. How many ways to create …

Leave a Reply

Your email address will not be published. Required fields are marked *