Let a class Person contains data members name and age. A constructor with two arguments
is used to assign name and age. Person is of two types a) Student and b) Teacher. class
Student contains data members i)course ii) Roll Number and iii)Marks and method
display() to display data related to student. Similarly, class Teacher contains data members
i) subject_assigned (May take this as a String) ii) contact_hour and method display () to
display data related to teacher. Implement this program using base class constructor in
derived class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
import java.util.Arrays;
public class Student extends Person {
private String course;
private int rollNumber;
private double[] marks;
public Student(String name, int age, String course, int rollNumber, double[] marks) {
super(name, age);
this.course = course;
this.rollNumber = rollNumber;
this.marks = marks;
}
public void display() {
System.out.println(getName() + ", age: " + getAge());
System.out.println("course: " + course + ", roll number: " + rollNumber + ", marks: " + Arrays.toString(marks));
}
}
public class Teacher extends Person {
private String subjectAssigned;
private int contactHour;
public Teacher(String name, int age, String subjectAssigned, int contactHour) {
super(name, age);
this.subjectAssigned = subjectAssigned;
this.contactHour = contactHour;
}
public void display() {
System.out.println(getName() + ", age: " + getAge());
System.out.println("subject assigned: " + subjectAssigned + ", contact hour: " + contactHour);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Tom Hall", 20, "CS", 21321, new double[]{65.4, 57, 90.5});
Teacher teacher = new Teacher("Anna Won", 37, "Java", 4);
student.display();
System.out.println();
teacher.display();
}
}
Comments
Leave a comment