Object Oriented Programming

Inheritance in Java

Inheritance is used to inherit another class' members, including fields and methods. A child class extends a parent class' members.


Syntax
modifier class className extends superClass {
    //to access a superClass member
    super.methodName();

    //to override a parent method with the same name
    @Override
    public parentMethodName(params){
    }
} ;

Notes

A child class inherits all members from the super class without direct implementation within the child class. If a method is written in the child class with the same name and parameters as one in the parent class, the parent class' method is overwritten. It is good practice to use the @Override annotation when overriding the parent method.

With class extension, when referring specifically to a super class member, use the keyword 'super'.


Example
public class Cat {
    string name;    
    public Cat() {
        this.name = "Garfield";        
    }    
    public String sound(){ //implemented sound method from the interface
        return "Meow!";
    }
} 

public class Tiger extends Cat { //the variable 'name' and the method 'sound()' are inherited
    public Tiger(){
        super(); //calling the constructor in the super class, Cat
    }

    @Override
    public String sound(){ //overwriting the sound() method in Cat
        return "Roar!";
    } 

    //This method is only for demonstrative purposes and is bad practice (you shouldn't override a method and call super elsewhere)
    public String catSound(){ 
        return super.sound(); //will call the sound method from the Cat parent class    
    }
}

See Also
Documentation

Java Tutorials - Inheritance

Add to Slack

< Class Methods   |   Interfaces >

© 2018 SyntaxDB. All Rights Reserved.