此时,父类和子类的名字是同一个,当然出来结果非你所想,super调用如下代码所示:
public class Hello{
public static void main(String[] args){
son a=new son();
a.name="小周";
a.age=18;
a.run(); //I'm son,I can fly!
//My name is 小周;age is 18
//My father's name is 小周;My father's age is 18
//I'm father,I can run!
//My name is 小周;age is 18
}
}
class father{
String name="老周";
int age=55;
public void run(){
System.out.println("I'm father,I can run!");
System.out.println("My name is " +this.name+ ";age is " +this.age);
}
}class son extends father{
String name; //这里,让子类覆盖父类的成员
int age;
public void run(){ //对父类的run()方法进行重写
System.out.println("I'm son,I can fly!");
System.out.println("My name is " +name+ ";age is " +age);
System.out.println("My father's name is " +super.name+ ";My father's age is " +super.age);
super.run();
}
}
public class Hello{
public static void main(String[] args){
son a=new son();
a.name="小周";
a.age=18;
a.run(); //I'm son,I can fly!
//My name is 小周;age is 18
//My father's name is 小周;My father's age is 18
//I'm father,I can run!
//My name is 小周;age is 18
}
}
class father{
String name="老周";
int age=55;
public void run(){
System.out.println("I'm father,I can run!");
System.out.println("My name is " +this.name+ ";age is " +this.age);
}
}class son extends father{
String name; //这里,让子类覆盖父类的成员
int age;
public void run(){ //对父类的run()方法进行重写
System.out.println("I'm son,I can fly!");
System.out.println("My name is " +name+ ";age is " +age);
System.out.println("My father's name is " +super.name+ ";My father's age is " +super.age);
super.run();
}
}
解决方案 »
- openoffice3.2 sdk linux安装和配置
- java难题 ,求解?
- javamail发信后收不到邮件
- 请教:<html:image page="/form/submit.bmp" property="submitBMP" />中的property的属性有什么作用?感谢。
- 大狭帮帮小第看看``数组问题`郁闷很久了在线等!!!
- 引用传值的问题
- 不知是我写错了,还是java有漏洞??????,不能用ASCII 30 做分隔符
- 我用的SpringLayout布局,请问怎么调整按钮大小阿,,setSize不行阿...
- 关于JDK安装的讨论!高人请进。
- 求救:如何用java或者javascript实现模拟键盘输入的方法?
- 我想让它去前一个页面,这怎么实现?
- 什么时候用Integer什么时候用int??
public static void main(String[] args){
son a=new son();
a.name="小周";
a.age=18;
a.run(); //I'm son,I can fly!
//My name is 小周;age is 18
//My father's name is 老周;My father's age is 55
//I'm father,I can run!
//My name is 老周;age is 55
}
}
这样似乎有些明白了,也就是说如果子类直接继承父类的属性时,则不会在创建对象时同时为属性开辟两个存储空间;如果是子类也有和父类相同的属性时,才会在创建对象时开辟两个存储空间来分别存储父类和子类的属性,是吗?
class father{
String name="老周";
int age=55;
public void run(){
System.out.println("I'm father,I can run!");
System.out.println("My name is " +this.name+ ";age is " +this.age);
}
}class son extends father{
String name;
int age;
public void run(){ //对父类的run()方法进行重写
System.out.println("I'm son,I can fly!");
System.out.println("My name is " +name+ ";age is " +age);
System.out.println("My father's name is " +super.name+ ";My father's age is " +super.age);
super.run();
}
}
如果没有同名的话,就和父类对象共用同一空间;所以你用子类引用修改了属性值,父类的也被修改了。
另外JAVA里方法是动态绑定的,方法的调用决定对象的类型。而属性决定于引用的类型。
而父类的两个属性是缺省的,所以不能在son类中访问,如果你的 son 类想访问父类的属性,那么父类的属性必须是 public 或 protected 的这跟什么内存分配什么的没什么关系