Super Class and Subclass

 

🔹 What is a Superclass?

A superclass (also called base class or parent class) is a class that is inherited by another class. It defines common attributes and methods that can be shared by other classes.

✅ Key points:

  • A superclass can be reused by multiple subclasses.

  • It may be abstract (not directly instantiated).

  • It provides common functionality to be extended or overridden.


🔹 What is a Subclass?

A subclass (also called derived class or child class) is a class that inherits from another class using the extends keyword. It can:

  • Use the methods and variables of the superclass.

  • Add new methods or fields.

  • Override superclass methods.


📌 Syntax of Inheritance in Java:

class Superclass { // fields and methods } class Subclass extends Superclass { // additional fields and methods }

📘 Example:

// Superclass
class Animal { void eat() { System.out.println("This animal eats food."); } } // Subclass class Dog extends Animal { void bark() { System.out.println("The dog barks."); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); myDog.eat(); // Inherited from Animal (superclass) myDog.bark(); // Defined in Dog (subclass) } }

Output:

This animal eats food.
The dog barks.

🧠 Key Differences

FeatureSuperclassSubclass
DefinitionClass being extended Class that extends another
Inheritance            RoleProvider of features Receiver of features
ReusabilityOffers reusable code Reuses and adds functionality
AccessCannot access subclass directly Can access superclass members

🔐 Accessing Superclass Members

A subclass can access public and protected members of the superclass. It cannot access private members directly.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine