question archive Creat a class Department with the following private member variables int did String dname Include appropriate getters and setters method in Department class
Subject:Computer SciencePrice:3.87 Bought7
Creat a class Department with the following private member variables
Include appropriate getters and setters method in Department class.
Create a class Student with the following private member variables
Include appropriate getters and setters method in Student class.
Creat a TestMain class which has main method.
In addition to main method, creat a method
public static Student createStudent() - All input as shown in the sameple input should be got in this method. Set the values to the Student object and return that object
Note : In main method, invoke the createStudent method and print the details of the object returned by that method.
Sample Input 1:
Enter the Department id:
100
Enter the Department name:
Computerscience
Enter the Student id:
123
Enter the Student name:
sudhaSample Output 1:
Department id:100
Department name:Computerscience
Student id:123
Student name:sudha
Answer:
//Department.java
class Department{ private int did; private String dname; public void setDid(int did){ this.did = did; } public void setDname(String dname){ this.dname = dname; } public int getDid(){ return this.did; } public String getDname(){ return this.dname; } }
//Student.java
class Student{ private int sid; private String sname; private Department department = new Department(); public void setSid(int sid){ this.sid = sid; } public void setSname(String sname){ this.sname = sname; } public void setDepartment(int did,String dname){ department.setDid(did); department.setDname(dname); } public int getSid(){ return this.sid; } public String getSname(){ return this.sname; } public void getDepartment(){ System.out.println("Department ID: "+department.getDid()); System.out.println("Department name: "+department.getDname()); } }
//TestMain.java
import java.util.Scanner; class TestMain { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); Student s = new Student(); int id; String name; System.out.print("Enter department id: "); id = scnr.nextInt(); System.out.print("Enter department name: "); name = scnr.next(); s.setDepartment(id, name); System.out.print("Enter student id: "); id = scnr.nextInt(); s.setSid(id); System.out.print("Enter student name: "); name = scnr.next(); s.setSname(name); System.out.println("\n"); s.getDepartment(); System.out.println("Student ID: "+s.getSid()); System.out.println("Student name: "+s.getSname()); } }
Step-by-step explanation
PFA