Java For Android Tutorial #19: Inheritance - Super and Override keywords...

Code:


package com.example;
public class java {
    public static void main(String[] str) {
        Child oChild = new Child("Accessing Child Class");
        oChild.show();
    }
}
class Parent{
    String parent;
    public Parent(String pInput){
        parent = pInput;
    }
    String dumy = "Hello";
    public void show(){
        System.out.println("Message from the parent class "+parent);
    }
}
class Child extends Parent{
    String child;
    public Child(String pInput){
        super("Accessing Parent");
        child = pInput;
    }
    @Override
    public void show(){
        super.show();
        System.out.println("Message from the child class "+child);
    }
}


When the constructor arguments are not empty then the child has to pass those arguments to the parent class. When a class inherits anything from the parent. It will do so, by triggering the constructor of the parent class. Coders will use a super keyword for passing the arguments. Super keyword is also used to access data in child class from the parent class. You can also override the functionalities of the parent class method by simply using override keyword in the child class.

Comments

Popular Posts