问大家一个问题

wangloveyang 2008-09-27 01:13:26

package chapter4;
class Person{
String name;
int age;

public void getInfo(){
System.out.println(name);
System.out.println(age);
}
}

public class Student{

public static void main(String[] args) {
Person p=new Person();
p.name="person";
p.age=30;
p.getInfo();

Student1 s=new Student1();
s.name="student1";
s.age=13;
s.school="school";
s.getInfo();
s.Study();
}

}

class Student1 extends Person{
String school=new String();

public void Study(){
System.out.println("Studding");
}
public void getInfo(String name,int age,String school){
super.getInfo();
System.out.println(school);
}
}

最后结果怎么不输出school

...全文
122 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangloveyang 2008-09-27
  • 打赏
  • 举报
回复
谢谢大家的帮忙,我已经明白了。来者都有分。
junjun1984 2008-09-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wangloveyang 的回复:]
public void getInfo(String school){
super.getInfo();
System.out.println(school);
这样就不能输出school,可把参数school删了,就能输出了请问怎么回事?
[/Quote]
删除了 s.getInfo();就匹配了子类中的getInfo方法了。所以输出了。它在子类中找到了合适的方法。
china_y 2008-09-27
  • 打赏
  • 举报
回复
2楼和3楼都能实现你的要求
你把方法的重写 和 重载 这2个概念改清楚就明白了
看仔细些,这是基础!努力~~呵。。。
ldxfsh 2008-09-27
  • 打赏
  • 举报
回复
楼主去把方法的重写 和 重载 这2个概念改清楚就明白了
wangloveyang 2008-09-27
  • 打赏
  • 举报
回复
public void getInfo(String school){
super.getInfo();
System.out.println(school);
这样就不能输出school,可把参数school删了,就能输出了请问怎么回事?
china_y 2008-09-27
  • 打赏
  • 举报
回复
public class Student{

public static void main(String[] args) {
Person p=new Person();
p.name="person";
p.age=30;
p.getInfo();

Student1 s=new Student1();
s.name="student1";
s.age=13;
s.school="school";
s.getInfo();
s.Study();
}
}
你main里的s.getInfo();调用的是Person类中的getInfo(),而不是Student1类中的。
所以如果想输出school,你需要把main函数中的s.getInfo()传进值,
改为:s.getInfo("student1",13,"school"); 这样是调用Student1类中的方法了
看看继承方面的知识,可能是你不小心马虎了呵呵。加油~
junjun1984 2008-09-27
  • 打赏
  • 举报
回复

class Person {
String name;

int age;

public void getInfo() {
System.out.println(name);
System.out.println(age);
}
}

public class Student {

public static void main(String[] args) {
Person p = new Person();
p.name = "person";
p.age = 30;
p.getInfo();

Student1 s = new Student1();
s.name = "student1";
s.age = 13;
s.getInfo("school");
s.Study();
}

}

class Student1 extends Person {
String school = new String();

public void Study() {
System.out.println("Studding");
}

public void getInfo(String school) {
super.getInfo();
System.out.println(school);
}
}
junjun1984 2008-09-27
  • 打赏
  • 举报
回复
你Student1里的getInfo是需要3个参数的,你 s.getInfo(); 其实是用了父类的getInfo。
而且 Student1里的getInfo:
public void getInfo(String school){}
就可以了。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧