Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
1.3 kB
2
Indexable
Never
// Abstract class
abstract class Person {
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Abstract method to display information
    public abstract void displayInfo();

    // Getter methods
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

// Derived class
class Student extends Person {
    private String studentId;
    private String major;

    // Constructor
    public Student(String name, int age, String studentId, String major) {
        super(name, age); // Call to the base class constructor
        this.studentId = studentId;
        this.major = major;
    }

    // Implement the abstract method
    @Override
    public void displayInfo() {
        System.out.println("Name: " + getName());
        System.out.println("Age: " + getAge());
        System.out.println("Student ID: " + studentId);
        System.out.println("Major: " + major);
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        // Create a Student object
        Student student = new Student("Alice", 20, "S12345", "Computer Science");

        // Display student information
        student.displayInfo();
    }
}
Leave a Comment