Computer ScienceNEB 2082
Write short notes on class and inheritance in oops with example. [5]
5Answer
Class and Inheritance in OOP with Example
Class
A class is a blueprint or template in Object-Oriented Programming (OOP) that defines the properties (attributes) and behaviors (methods) of objects. It acts as a logical entity that groups related data and functions.
Example:
class Student {
// Attributes (data members)
String name;
int rollNo;
// Methods (member functions)
void display() {
System.out.println("Name: " + name + ", Roll No: " + rollNo);
}
}
Here, Student is a class with attributes (name, rollNo) and a method (display()).
Inheritance
Inheritance is a mechanism in OOP where a new class (subclass or child class) inherits properties and methods from an existing class (superclass or parent class). It promotes code reusability and establishes a hierarchical relationship between classes.
Types of Inheritance:
- Single Inheritance – A subclass inherits from only one superclass.
- Multilevel Inheritance – A subclass inherits from another subclass.
- Multiple Inheritance – A subclass inherits from multiple superclasses (not supported in Java but possible in C++ using interfaces).
- Hierarchical Inheritance – Multiple subclasses inherit from a single superclass.
Example (Single Inheritance):
class Animal { // Superclass
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal { // Subclass (inherits from Animal)
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Own method
}
}
Output:
Eating...
Barking...
Explanation:
Doginherits theeat()method fromAnimal.Dogalso has its own methodbark().- This reduces code duplication and improves maintainability.
Advantages of Inheritance:
- Reusability – Code from the parent class can be reused.
- Extensibility – New features can be added without modifying existing code.
- Hierarchical Classification – Models real-world relationships (e.g.,
Dogis anAnimal).
Disadvantages:
- Tight Coupling – Changes in the parent class may affect subclasses.
- Complexity – Overuse can make the program hard to understand.
Inheritance is a fundamental concept in OOP that helps in creating modular, scalable, and efficient programs.
Discussion
Loading…