Skip to main content

ProwessApps

Learn · Practice · Excel

Create a class Student which store the name and roll no. of a student. Create another class Marks which inherits class Student and store the marks of 3 subjects. Create Class Result which inherits class Marks and store the information of a student and display name, roll and total marks of a student.

Java Code Example — Inheritance Programs

ADVERTISEMENT

Create a class Student which store the name and roll no. of a student. Create another class Marks which inherits class Student and store the marks of 3 subjects. Create Class Result which inherits class Marks and store the information of a student and display name, roll and total marks of a student.

Objective

Write a Java program to demonstrate Multilevel Inheritance by calculating student marks.

Algorithm / Approach

  1. Create a base class Student with name and roll fields.
  2. Create an intermediate class Marks that extends Student and holds marks for three subjects.
  3. Create a derived class Result that extends Marks with an input() and display() method.
  4. In the main method, instantiate the Result class and call its methods.
Student.java
import java.util.Scanner;
class Student {
 String name;
 int roll;
}
class Marks extends Student {
 int m1,m2,m3;
}
class Result extends Marks {
 int total;
 void input() {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Name: ");
  name = s.nextLine();
  System.out.print("Enter Roll: ");
  roll = Integer.parseInt(s.nextLine());
  System.out.print("Enter Marks1: ");
  m1 = Integer.parseInt(s.nextLine());
  System.out.print("Enter Marks2: ");
  m2 = Integer.parseInt(s.nextLine());
  System.out.print("Enter Marks3: ");
  m3 = Integer.parseInt(s.nextLine());
 }
 void display() {
  total = m1+m2+m3;
  System.out.println("Name- "+name);
  System.out.println("Roll- "+roll);
  System.out.println("Total- "+total); 
 }
}
class Test {
 public static void main(String[] a)
 {
  Result r = new Result();
  r.input();
  r.display();
 }
}

Expected Output

Enter Name: Ayan
Enter Roll: 12
Enter Marks1: 90
Enter Marks2: 90
Enter Marks3: 90
Name- Ayan
Roll- 12
Total- 270

Explanation of the Program

  • Inheritance allows a new class to absorb the properties and methods of an existing class. This is called an IS-A relationship.
  • Multilevel inheritance occurs when a derived class is created from another derived class (e.g., A -> B -> C).
  • Even though the Result class doesn't explicitly declare the name or m1 variables, it has access to them because they are inherited down the chain from its parent classes.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT