Question No. 2: Answer the following questions? ( 15 Marks ) [ CLO2 ]
Make a class named Person
o It has two attributes name, for person name, as a character array of size 50 and age, for a
person’s age as a positive integer.
o Make a function named get() to get a person’s name and age from user.
o Make a function named show() to show a person’s name and age on screen.
o Make a child class named Student and privately inherit this class from Person class.
o It has one attribute gpa, as a float data type.
o Make a function named get() to get name, age and gpa of a student from user.
o Make a function named show() to show the name, age and gpa of a student on screen.
o In the main() function make a Student object and call get() and show() functions through this
object and close the program.
//importing util to take input from user
import java.util.*;
public class Main
{
public static void main(String[] args) {
//creating object for Student class
Student s1 = new Student();
//calling methods in Student class
s1.Get_Data();
s1.Show_Data();
}
}
//Person class
class Person
{
//declaring the given variables as private
private char[] name = new char[50];
private int age;
//no argument constructor
Person()
{
//initializing to empty string
name = "".toCharArray();
//initializing to 0
age = 0;
}
//argument constructor
Person(String name, int age)
{
this.name = name.toCharArray();
this.age = age;
}
//Get_Data method to take input from user
void Get_Data()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter name: ");
String s = ob.nextLine();
name = s.toCharArray();
System.out.print("Enter age: ");
age = ob.nextInt();
}
//to print data
void Show_Data()
{
System.out.println("Name: "+new String(name)+"\nAge: "+age);
}
}
//Student class extends person class
class Student extends Person
{
//declaring variables
private char[] degree = new char[50];
private double gpa;
//no argument constructor
Student()
{
//calling parent class no argument constructor
super();
degree = "".toCharArray();
gpa = 0;
}
//argument constructor
Student(String name, int age, String degree, double gpa)
{
//calling parent class argument constructor to initialize name and age
super(name,age);
this.degree = degree.toCharArray();
this.gpa = gpa;
}
//Override method Get_Data
void Get_Data()
{
//calling parent class Get_Data method
super.Get_Data();
Scanner ob = new Scanner(System.in);
System.out.print("Enter degree: ");
String s = ob.nextLine();
degree = s.toCharArray();
System.out.print("Enter gpa: ");
gpa = ob.nextDouble();
}
//Override method Show_Data
void Show_Data()
{
//calling parent class Show_Data method
super.Show_Data();
System.out.println("Degree: "+new String(degree)+"\nGPA: "+gpa);
}
}
Comments
Leave a comment