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
- Create a base class
Studentwithnameandrollfields. - Create an intermediate class
Marksthat extendsStudentand holds marks for three subjects. - Create a derived class
Resultthat extendsMarkswith aninput()anddisplay()method. - In the
mainmethod, instantiate theResultclass 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
Resultclass doesn't explicitly declare thenameorm1variables, 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)