class A
{
public static String s="AAAA";
} class B extends A
{ public static String s="BBBB"; //重新定义s,是何居心?
public static void main(String[] args)
{
A a = new B(); //这里很不理解;为什么用B来生成的对象,输出时是
System.out.println(a.s); //AAAA
} } 这个问题看似简单,好象挺难理解透的
{
public static String s="AAAA";
} class B extends A
{ public static String s="BBBB"; //重新定义s,是何居心?
public static void main(String[] args)
{
A a = new B(); //这里很不理解;为什么用B来生成的对象,输出时是
System.out.println(a.s); //AAAA
} } 这个问题看似简单,好象挺难理解透的
如果没有前面的A,那么a肯定是B类型,现在a前面明显有类型说明A,所以a.s=AAAA
可以这样理解吧
class Base{
String var="Base's var";
static String var1="Base's static var1 ";
public Base(){}
public void method(){
System.out.println("method of Base");
}
public static void method1(){
System.out.println("static method of Base");
}
}
public class Sub extends Base{
String var="Sub's var";
static String var1="Sub's static var";
public void method(){
System.out.println("method of sub");
}
public static void method1(){
System.out.println("static method of sub");
}
public static void main(String args []){
Base who=new Sub();//who被声明为Base类型,引用Sub实例
System.out.println("who's var="+who.var);
System.out.println("who.static var1="+who.var1);
who.method();
who.method1();
}
}运行结果
who's var=Base's var
who.static var1=Base's static var1
method of sub
static method of Base
你在B类中再加一个变量就会明显很多,比如你在B中再加个
public static String s1="CCCC";
a.s1是根本看不到的~~
strUCture for objects. In Sun's current implementation of the Java Virtual Machine, a reference to a class instance is a pointer to a handle that is itself a pair of pointers: one to a table containing the methods of the object and a pointer to the Class object that represents the type of the object, and the other to the memory allocated from the Java heap for the object data." 实际上就是说:在java虚拟机中,类实例的引用就是指向一个句柄(handle)的指针,这个句柄是一对指针:一个指针指向一张表格,实际上这个表格也有两个指针:一个指针指向一个包含了对象的方法表,另外一个指向类对象;另一个指针指向一块从java堆中为分配出来内存空间。原文http://blog.csdn.net/yirentianran/archive/2008/04/25/2327349.aspx
{
public static String s="AAAA";
} class B extends A
{ public static String s="BBBB"; //重新定义s,是何居心?
这样做的意义何在???
父类中的s与子类中的s占的是独立的存储空间。
a 是A对象的实例
执行a.s
当然引用A类的属性方法了
其实改成如下也是一样的结果:
class A
{
public static String s="AAAA";
} class B extends A
{ public static String s="BBBB"; //重新定义s,是何居心?
public static void main(String[] args)
{
A a = new B(); //这里很不理解;为什么用B来生成的对象,输出时是
System.out.println(A.s); //AAAA
} }
静态方法 可以直接用类名引用 既 A.SS
A a = new B();
在JAVA中会把a.s 看作是Super.s 或者是 A.s这里有句很罗嗦的讲法 执行 a.s 可以这么说 调用a引用所指向的引用类型就是A也就是 A.s
也就是java中静态属性或方法不存在多态
也就是说s是一个static 的静态变量
在父类中定义过后就不能被改变了
所以B中的public static s="BBB"并不能将A中的改变