BlogJava-Love Java-文章分类-java个人问题区http://www.blogjava.net/Nail/category/27252.htmlzh-cnSat, 10 Nov 2007 19:56:46 GMTSat, 10 Nov 2007 19:56:46 GMT60声明为父类的子类实例 在调用成员变量和方法时,调用的是父类,还是子类的?(子类和父类的成员变量和方法名相同)http://www.blogjava.net/Nail/articles/159625.htmlNailNailSat, 10 Nov 2007 13:44:00 GMThttp://www.blogjava.net/Nail/articles/159625.htmlhttp://www.blogjava.net/Nail/comments/159625.htmlhttp://www.blogjava.net/Nail/articles/159625.html#Feedback0http://www.blogjava.net/Nail/comments/commentRss/159625.htmlhttp://www.blogjava.net/Nail/services/trackbacks/159625.htmlclass 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
 }
 
}

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

Nail 2007-11-10 21:44 发表评论
]]>