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, store the information of a student and display name, roll and total marks of a student. Use super keyword to take input.

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, 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

  1. Create a base class Student with an input() method for name and roll.
  2. Create a derived class Result with its own input() method for marks.
  3. Inside the child's input() method, use super.input() to call the parent's version first.
  4. Create a Result object in main and call its input() 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 a Result object, 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 super keyword (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 of super.input() inside the child method, which causes infinite recursion (the method repeatedly calls itself) and results in a StackOverflowError.
ADVERTISEMENT