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, store the information of a student and display name, roll and total marks of a student. Use super keyword to take input.
Objective
Write a Java program to demonstrate the use of the super keyword to call a parent class method.
Algorithm / Approach
- Create a base class
Studentwith aninput()method for name and roll. - Create a derived class
Resultwith its owninput()method for marks. - Inside the child's
input()method, usesuper.input()to call the parent's version first. - Create a
Resultobject in main and call itsinput()method.
Student.java
import java.util.Scanner;
class Student {
String name;
int roll;
Scanner s=new Scanner(System.in);
void input(){
System.out.print("Enter Name: ");
name = s.nextLine();
System.out.print("Enter Roll: ");
roll = Integer.parseInt(s.nextLine());
}
}
class Result extends Student {
int m1,m2,m3,total;
void input() {
super.input();
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: Sangeet Enter Roll: 12 Enter Marks1: 90 Enter Marks2: 90 Enter Marks3: 90 Name- Sangeet Roll- 12 Total- 270
Explanation of the Program
- When a child class declares a method with the exact same name and signature as a method in its parent class, it is called Method Overriding.
- If you call
input()on aResultobject, Java will only execute the child's version, completely ignoring the parent's version. - To ensure the parent's logic still executes, we use the
superkeyword (e.g.,super.input()). This acts as a direct line to the immediate parent class, forcing it to run the overridden method.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Calling
input()instead ofsuper.input()inside the child method, which causes infinite recursion (the method repeatedly calls itself) and results in a StackOverflowError.