日期:2014-05-20  浏览次数:20772 次

子类继承父类问题
class   Person
{
private   String   name;
private   int     age;
public   Person(String   name,int   age)
{
this.name=name;
this.age=age;
}

public   void   print()
{
System.out.println( "Name: "+name+ "\nage: "+age);
}
}
class   Student   extends   Person
{
int   stuid;

}
public   class   test1
{

public   static   void   main(String   args[])
{
Person   a=new   Person( "mark ",20);
a.print();

Student   b=new   Student( "susan ",22);

b.print();
}
}
怎样输出子类里的stuid?

------解决方案--------------------
class Student extends Person
{
int stuid;
public void print()
{
System.out.println( "Name: "+name+ "\nage: "+age+ "\nstuid: "+stuid);
}


}
------解决方案--------------------
class Person{
private String name;

private int age;

public Person(String name,int age){

this.name=name;
this.age=age;
}

public void print(){

System.out.println( "Name: "+name+ "\nage: "+age);
}

public String toString(){

return get.Class().get.Name()+
"[姓名: "+name+ " "+ "年龄: "+age+ "] ";

}
}


class Student extends Person{

private int stuid;

public Student(String name, int age, int stuid){

super(name,age);
this.stuid = stuid;

}

public void setStuid(int stuid){

this.stuid = stuid;

}

public int getStuid(){

return stuid;

}


public String toString(){

return super.toString()+
"[stuid= "+stuid+ "] ";

}

}

public class Test1{

public static void main(String[] args){

Person a = new Student( "谁谁. ",26,4589);
System.out.println(a.getStuid);

System.out.println(a);

}


}

------解决方案--------------------
新建java学习群31317654,欢迎初学者和高手们加入
------解决方案--------------------

class Person{
private String name;

private int age;

public Person(String name,int age){

this.name=name;
this.age=age;
}

public void print(){

System.out.println( "Name: "+name+ "\nage: "+age);
}

public String toString(){

return ( "姓名: "+name+ " "+ "年龄 "+age);

}
}


class Student extends Person{

private int stuid;

public Student(String name, int age, int stuid){

super(name,age);
this.stuid = stuid;

}

public void setStuid(int stuid){

this.stuid = stuid;