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 data structure that contains both data and functions to manipulate that data.
Example:
class Car {
// Attributes (data members)
String model;
String color;
// Methods (functions)
void start() {
System.out.println("Car started.");
}
}
Here, Car is a class with attributes (model, color) and a method (start()).
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 of Inheritance
// Parent class (Superclass)
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Child class (Subclass) inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark(); // Own method
}
}
Output:
Eating...
Barking...
Explanation:
Animalis the parent class with a methodeat().Dogis the child class that inheritseat()fromAnimaland adds its own methodbark().- The
extendskeyword is used to establish inheritance.
Advantages of Inheritance:
- Code Reusability – Avoids rewriting the same code.
- Method Overriding – Child class can modify inherited methods.
- Polymorphism – Allows objects to be treated as instances of their parent class.
Inheritance helps in creating a structured and modular program by organizing classes in a hierarchy.
Discussion
Loading…