java program for student details using inheritance
Java program to print student details using "single-level" inheritance
In this section, you will learn how to print student details using single inheritance in Java, with Scanner and without Scanner class.
With Scanner class
Interactive input using Scanner for user data entry
Note: This method uses the Scanner class to get input from the user at runtime. The program prompts for student details and displays them.
Example Code:
→ File: student.java
import java.util.Scanner;
class StudentDetails {
int roll_no;
String name, cl;
//creating a function to take student details
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll Number: ");
roll_no = sc.nextInt(); //=> 22\n == buffer
sc.nextLine(); // => \n
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter class: ");
cl = sc.nextLine();
}
}
class Student extends StudentDetails {
//method to display student details
void display() {
System.out.println("/******* Student details printed ********/");
System.out.println("Roll Number is: "+roll_no);
System.out.println("Your name is: "+name);
System.out.println("Your class is: "+cl);
}
public static void main(String args[]) {
Student obj = new Student();
obj.input();
obj.display();
}
}
Output:
✓ Console Output
Without Scanner class
Hard-coded values passed directly to methods
Note: This method uses parameters to pass student details directly. Useful when data is already known or when testing multiple students.
Example Code:
→ File: student.java
class StudentDetails {
int roll_no;
String name, cl;
//creating a function to take student details
void input(int roll, String nam, String cl_name) {
roll_no = roll;
name = nam;
cl = cl_name;
}
}
class Student extends StudentDetails {
//method to display student details
void display() {
System.out.println("\n/******* Student details printed ********/");
System.out.println("Roll Number is: "+roll_no);
System.out.println("Your name is: "+name);
System.out.println("Your class is: "+cl);
}
public static void main(String args[]) {
Student std1 = new Student();
std1.input(20, "Ankaj Gupta", "12th");
std1.display();
Student std2 = new Student();
std2.input(10, "Anmol kumar", "10th");
std2.display();
}
}
Output:
✓ Console Output