黑马程序员技术交流社区
标题:
子类继承父类方法后调用子类的属性
[打印本页]
作者:
耿文达
时间:
2013-5-12 18:49
标题:
子类继承父类方法后调用子类的属性
本帖最后由 耿文达 于 2013-5-12 20:06 编辑
有一个类Person,具有姓名、国籍两个属性,还有一个SayHello方法,方法执行时输出“我是***我来自***”;然后定义一个Chinese类从Person类继承,现在想用继承的父类的SayHello方法调用子类的特有的姓名、国籍两个属性,而不用复写,请问怎样才能做到?我自己写了一段代码,但是只能调用父类的属性,无法调用子类的,这是为什么?请高手指教
class Person
{
String name;
String country;
public void SayHello()
{
System.out.println("我是"+name+','+"我来自"+country);
}
}
class Chinese extends Person
{
String name = "张三";
String country = "中国";
}
public class Test {
public static void main(String[] args)
{
Person c = new Chinese();
c.SayHello();
}
}
复制代码
作者:
萌小子
时间:
2013-5-12 19:16
可以这样理解,对于子类你只告诉了她有这个方法,你并没有告诉她这个方法是怎么样的,要怎么做。
作者:
蚂蚁搬家
时间:
2013-5-12 19:22
父类对象的引用无法调用子类中特有的方法和属性,这个好像只能重写了
作者:
蔡增辉
时间:
2013-5-12 19:24
本帖最后由 蔡增辉 于 2013-5-12 19:25 编辑
你的代码有问题,你在子类中重新声明了变量name,和country,
(注意你在子类中用了
String
name,
String
country)
这样系统认为子类中的name 和 country不是父类中的name和country,
而c.SayHello() 调用的是父类中方法,所以不能访问子类的成员变量;
作者:
小陈期待逆袭
时间:
2013-5-12 19:37
我测试过了可以通过,你参考一下吧,但是我觉得这样的构思有点问题 希望可以帮助到你
class Person
{
String name;
String country;
Person(){};
Person(String name,String country)
{
this.name=name;
this.country=country;
}
public void sayHello()
{
System.out.println("我是"+this.name+','+"我来自"+this.country);
}
}
class Chinese extends Person
{
static String country="Chinese";
Chinese(){};
Chinese(String name)
{
super(name,country);
}
}
class Test
{
public static void main(String[] args)
{
Chinese c = new Chinese("张三");
c.sayHello();
}
}
作者:
赵利斌
时间:
2013-5-12 20:03
这样吧:代码如下:
class Person
{
String name;
String country;
Person(String name,String country)
{
this.name=name;
this.country=country;
}
public void sayHello()
{
System.out.println("我是"+this.name+','+"我来自"+this.country);
}
}
class Chinese extends Person
{
Chinese(String name,String country)
{
super(name,country);
}
}
class Demo
{
public static void main(String[] args)
{
Person c = new Chinese("张三","中国");
c.sayHello();
}
}
作者:
仲伟
时间:
2013-5-12 20:03
Person(){};
Person(String name,String country)
{
this.name=name;
this.country=country;
}
这个构造必须的,而且继承构造方法和属性
作者:
赵利斌
时间:
2013-5-12 20:05
这样写就用上了多态 是这样的嘛!
作者:
沐有鱼丸
时间:
2013-5-12 20:07
感觉只能重写方法样
作者:
炉海佳
时间:
2013-5-12 20:13
class Person
{
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public void SayHello()
{
System.out.println("我是"+name+','+"我来自"+country);
}
}
class Chinese extends Person
{
}
public class Test {
public static void main(String[] args)
{
Person p = new Person();
p.setName("lisi");
p.setCountry("亚洲");
p.SayHello();
Chinese c=new Chinese();
c.setCountry("中国");
c.setName("张三");
c.SayHello();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2