Computer ScienceNEB 2082

Write short notes on class and inheritance in oops with example. [5]

5

Answer

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:

  1. Single Inheritance – A subclass inherits from only one superclass.
  2. Multilevel Inheritance – A subclass inherits from another subclass.
  3. Multiple Inheritance – A subclass inherits from multiple superclasses (not supported in Java but possible in C++ using interfaces).
  4. 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:

  • Animal is the parent class with a method eat().
  • Dog is the child class that inherits eat() from Animal and adds its own method bark().
  • The extends keyword 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…

More Computer Science questions

All Computer Science old questions