About Lesson
Sub-Class or Derived Class or Child Class is a class that inherits fields and methods from another class called the super-class or parent class.
class SuperClass {
// fields and methods
}
class SubClass extends SuperClass {
// additional fields and methods
}
Features:
- Sub-classes inherits all non-private fields and methods from their super-class.
- Method Overriding: Sub-classes can provide specific implementations for methods that are already defined in the super-class.
- Accessing Super-Class members: Sub-classes can access the fields and methods of the super-class using the
super
keyword. - Private members of the super-class are not accessible directly by the sub-class. However, they can be accessed through public or protected getter and setter methods.
// Super-class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Sub-class
class Dog extends Animal {
@Override
void sound() {
super.sound(); // Calls the sound() method of Animal
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
}