public class Temp {
int t; //实例变量 public static void main(String args[]){
int t=1; //局部变量 System.out.println(t); //打印局部变量 Temp a= new Temp(); //创建实例
System.out.println(a.t); //通过实例访问实例变量 }
}
结果为: 1 0 (成员变量具有缺省值 而局部变量则没有)
把代码改为
public class Temp {
static int t; //类变量 public static void main(String args[]){
System.out.println(
t); //打印类变量
int t=1; //局部变量 System.out.println(
t); //打印局部变量
Temp a= new Temp(); //创建实例
System.out.println(
a.t); //通过实例访问实例变量
}
}
package mypack2;
import mypack1.ClassA;
class ClassC extends mypack1.ClassA{
public void method(){
ClassA a = new ClassA();
a.var1=1;
super.var2=1; ClassC c = new ClassC(); c.var1=1;
c.var2=1; }
}
OK,用java in a nutshell中的一段话来总结一下全文:
protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.
类体由2部分构成:一部分是变量的定义;一部分是方法的定义(一个类中可以有多个方法)在变量定义部分定义的变量叫做类的成员变量,成员变量在整个类中都有效.(全局变量应该是成员变量的俗称)在方法体中定义的变量叫做局部变量,局部变量只在定义它的方法中有效.成员变量又分为实例变量和类变量(static静态变量).class One{ f