Child Class can extend single Parent Class by adding extends ParentClassName after Child Class Name.
Child Class can reference Parent's Properties and Methods as they were their own.
You can use Keyword super to reference Parent's Properties and Methods when Child has Properties and Methods with
the same name and signature like: super.name, super.displayName().
Use @Override Annotation just to indicate to Compiler your intention to override existing Parent's Method.
Syntax
class Soldier extends Person { }
Extend Class
//===========================================================================================================
// CLASS: Test
//===========================================================================================================
public class Test {
public static void main(String[] args) {
Soldier john = new Soldier(); //Create Instance of Class Soldier
john.displayName(); //Reference Child's Method.
john.greetSoldier(); //Reference Child's Method.
john.greetPerson(); //Reference Parent's Method (inherited).
Integer age = john.age; //Reference Parent's Property (inherited).
}
}
//===========================================================================================================
// CLASS: Person
//===========================================================================================================
class Person {
String name = "John";
Integer age = 20;
void displayName() { System.out.println("Person " + name); }
void greetPerson() { System.out.println(name + " is Person"); }
}
//===========================================================================================================
// CLASS: Soldier
//===========================================================================================================
class Soldier extends Person {
String name = "John the killer";
@Override //Intention to override Parent's Method
void displayName () { System.out.println("Soldier " + super.name); }//Reference Parent's Property
void greetSoldier() { super.displayName(); }//Reference Parent's Method
}