// Abstract class: Person
abstract class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public abstract void displayDetails();
public void greet() {
System.out.println("Hello, I am " + name + ".");
}
}
// Subclass: Student
class Student extends Person {
private int studentId;
public Student(String name, int age, int studentId) {
super(name, age);
this.studentId = studentId;
}
@Override
public void displayDetails() {
System.out.println("Student - Name: " + super.getName() + ", Age: " + super.getAge() +
", Student ID: " + studentId);
}
public void study() {
System.out.println("Student is studying.");
}
}
// Subclass: Faculty
class Faculty extends Person {
private String department;
public Faculty(String name, int age, String department) {
super(name, age);
this.department = department;
}
@Override
public void displayDetails() {
System.out.println("Faculty - Name: " + super.getName() + ", Age: " + super.getAge() +
", Department: " + department);
}
public void teach() {
System.out.println("Faculty is teaching.");
}
}
public class PersonExample {
public static void main(String[] args) {
Student student = new Student("John", 20, 123);
Faculty faculty = new Faculty("Dr. Smith", 35, "Computer Science");
student.displayDetails();
student.greet();
student.study();
System.out.println();
faculty.displayDetails();
faculty.greet();
faculty.teach();
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter