?– A super class is a class that is inherited whereas sub class is a class that does the inheriting.
In Java, a superclass (or parent class) is a class that is extended by another class, known as the subclass (or child class). The relationship between a superclass and a subclass is part of the concept of inheritance in object-oriented programming. Here are some key differences between a superclass and a subclass:
- Definition:
- Superclass: It is the class that is extended or inherited from.
- Subclass: It is the class that extends or inherits from another class.
- Inheritance:
- Superclass: It provides common attributes and behaviors to be shared by its subclasses.
- Subclass: It inherits the attributes and behaviors from its superclass and can also have its own unique attributes and behaviors.
- Access to Members:
- Superclass: It can have both public and protected members.
- Subclass: It can access public and protected members of its superclass, but it cannot access private members directly.
- Keyword:
- Superclass: It is often referred to as the base class or parent class.
- Subclass: It is often referred to as the derived class or child class.
- Example:
java
// Superclass
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
In this example,
Dog
is the subclass that extends theAnimal
superclass. - Usage:
- Superclass: It is a more general and abstract concept.
- Subclass: It is more specialized and can add specific functionalities to the general features provided by the superclass.
In summary, a superclass is a more general class that provides common functionality, while a subclass is a more specialized class that inherits from the superclass and may add or override specific behaviors.