Inheritance
The extends keyword specifies the parent class. Only one parent class is allowed.
You can apply the keyword final to disable inheritance from this class.
If the parent class does not have a default constructor, then the child class must call one of the parent constructors in its own constructor in the first executable line.
Java supports polymorphism. It means that child class can override a parent method.
Fields in child class will shadow fields of parent class with same name.
public class Parent{
protected int field1;
protected int field2;
Parent(int a){}
public void method1(){}
}
public class Child extends Parent {
Child(){
int b = 34;
super(23);
}
public void method3(){
field1 = 10; // change parent field
method1(); // call parent method
}
}
// final class, you can't inherit from it
public final class Parent1{}
public class Child1 extends Parent1{}
polymorphism
Child class can override parent method. The @Override annotation is used to ensure that you are overriding a method and not defining a new method.
You can declare a method with the keyword final to disable overriding in child classes.
public class Parent{
public void method1(){}
public final void method2(){}
}
class Child extends Parent {
@Override
public void method1(){
// doing other stuff ...
}
// error, method2() is final method
@Override
public void method2(){}
// but overloading is allowed
public void method2(int arg){
// ...
}
}
parent reference
The super keyword specifies a reference to the parent class.
class Parent{
int shadow = 10;
public void method1(){}
public void method2(){}
}
class Child extends Parent {
int shadow = -10;
@Override
public void method1(){
System.out.println(shadow); // -10
System.out.println(this.shadow); // -10
System.out.println(super.shadow); // 10
}
@Override
public void method2(){
// ... doing child stuff before parent class stuff
super.method1(); // doing parent class stuff
// ... doing child stuff before parent class stuff
}
}