Love Java

声明为父类的子类实例 在调用成员变量和方法时,调用的是父类,还是子类的?(子类和父类的成员变量和方法名相同)

class Base
{
 String str="BaseStr";
 String staticstr="Base static str";
 void method()
 {
  System.out.print("BaseMethod");
 }
 static void staticMethod()
 {
  System.out.print("Base Static Method");
 }
}

class Sub extends Base
{
 String str="SubStr";
 String staticstr="Sub static str";
 void method()
 {
  System.out.print("SubMethod");
 }
 static void staticMethod()
 {
  System.out.print("Sub static Method");
 }
}
public class BaseType_SubInstance
{
 public static void main(String[] args)
 {
  Base x=new Sub();
  System.out.println("x.str:"+x.str);  //打印 x.str:BaseStr
  System.out.println("x.staticstr:"+x.staticstr);//打印 x.staticstr:Base static str
  System.out.print("x.method():");
  x.method();         //打印 SubMethod           
  System.out.print("\nx.staticMethod():");
  x.staticMethod(); //打印 Base Static Method
 }
 
}

为什么结果打印结果会是那样?

posted on 2007-11-10 21:44 Nail 阅读(1784) 评论(2)  编辑  收藏 所属分类: java个人问题区

Feedback

# re: 声明为父类的子类实例 在调用成员变量和方法时,调用的是父类,还是子类的?(子类和父类的成员变量和方法名相同) 2008-04-04 09:49 webbestar

调用无参方法是,系统会默认调用子类的无参方法先  回复  更多评论   

# re: 声明为父类的子类实例 在调用成员变量和方法时,调用的是父类,还是子类的?(子类和父类的成员变量和方法名相同) 2009-05-09 07:35 xx

实施上述  回复  更多评论   



只有注册用户登录后才能发表评论。


网站导航:
 

My Links

Blog Stats

留言簿

文章分类

文章档案

Applications

java

文学

搜索

最新评论