java类与对象的基础题

2024-11-22 23:02:33
推荐回答(1个)
回答1:

//Student 类
class Student{
String name;
int age;
Student(String name,int age){
this.age=age;
this.name=name;
}
Student(){}

public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
}
//Unergraduate类
class Undergraduate extends Student{
String specially;
Undergraduate(String n,int a,String s){
name = n;
age = a;
specially = s;
}
Undergraduate(){}

public void setSpecially(String specially){
this.specially = specially;
}
public String getSpecially(){
return specially;
}
}
//Postgraduate类
class Postgraduate extends Student{
String studydirection;
Postgraduate(String n,int a,String s){
name = n;
age = a;
studydirection = s;
}
Postgraduate(){}
public void setStudydirection(String studydirection){
this.studydirection = studydirection;
}
public String getStudydirection(){
return studydirection;
}
}

public class TestStudent{ //程序入口
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu1 = new Student("Tom",19);
Student stu2 = new Student("Anna",20);
Postgraduate stu3 = new Postgraduate("John",25,"Computer Science");
Postgraduate stu4 = new Postgraduate("Lucy",24,"Chinese");
Undergraduate stu5 = new Undergraduate("Ansen",21,"Math");
Student[] data = {stu1,stu2,stu3,stu4,stu5}; //Student类的数组
System.out.println("Name\tAge");
System.out.println("--------------");
System.out.println(stu1.getName()+"\t"+stu1.getAge());
System.out.println(stu2.getName()+"\t"+stu2.getAge());
System.out.println(stu3.getName()+"\t"+stu3.getAge()+"\t"+stu3.getStudydirection());
System.out.println(stu4.getName()+"\t"+stu4.getAge()+"\t"+stu4.getStudydirection());
System.out.println(stu5.getName()+"\t"+stu5.getAge()+"\t"+stu5.getSpecially());
System.out.println("--------------");
data[0].setName("汤姆");
stu2.setName("约翰");
for(int i=0;i System.out.println(data[i].getName());

}
}