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

[java]public class Parent {

private String output = "hallo";

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

public void print() {
System.out.println(output );
}
}
[/java]

Child.java

[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");
}*/
}
[/java]

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

Add a Comment

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