In: Computer Science
java programing
Q: Given the following class:
public class Student {
private String firstName;
private String lastName;
private int age;
private University university;
public Student(String firstName, String lastName, int age, University university) {
this.firstName = fisrtName;
this.lastName = lastName;
this.age = age;
this.university = university;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public University getUniversity(){
return university;
}
public String toString() {
return "\nFirst name:" + firstName + "\nLast name:" + lastName + " \nAge:"+ age + "\nUniversity" + university;
}
}
a- Create the University class (data type). The class must include name, state, and the country as member variables; it must also include methods for returning and storing the name, state, and country.
b- Create client code to test the classes.
Code:
import java.util.*;
class University{
private String name;
private String state;
private String country;
public University(String name, String state, String country) {
this.name = name;
this.state = state;
this.country = country;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", state='" + getState() + "'" +
", country='" + getCountry() + "'" +
"}";
}
}
class Student {
private String firstName;
private String lastName;
private int age;
private University university;
public Student(String firstName, String lastName, int age, University university) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.university = university;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public University getUniversity() {
return university;
}
public String toString() {
return "\nFirst name:" + firstName + "\nLast name:" + lastName + " \nAge:" + age + "\nUniversity" + university;
}
}
class Main {
public static void main(String args[]) {
University u1 = new University("University of California", "California", "USA");
Student s1 = new Student("Javed","Akhtar",22,u1);
System.out.println(s1.toString());
}
}
Code output:
Code Screenshot: