
请教下网上的高手在java中动态成员变量怎样理解,能举个例吗? 5
展开全部
在运行过程中,成员变量(包括静态变量和实例变量)以及静态方法都和引用变量的声明类型绑定, 实例方法将和实例绑定.举例如下:
class Father{
private int private_var;
static int static_var;
public int public_var;
private void private_method(){}
static void static_method(){}
public void public_method(){}
}
class Son extends Father{
private int private_var;
static int static_var;
public int public_var;
private void private_method(){}
static void static_method(){}
}
以上代码中,子类Son和父类Father具有同名的变量和方法.对于以下代码,引用变量f声明为Father类型,实际引用的是Son的实例,那么通过变量f来访问成员变量和方法,绑定关系如下:
Father f=new Son();
int v1=f.private_var; //bind with father's private_var
int v2=f.static_var; //bind with father's static_var
int v3=f.public_var; //bind with father's public_var
f.private_method(); //bind with father's private_method
f.static_method(); //bind with father's static_method
f.public_method(); //bind with son's public_method
我个人的理解是方正就是把子类强制转换成父类对象,这样当你有多个不同的继承自父类的子类时,实际用的时候用的方法和变量都会是各自对应的子类
class Father{
private int private_var;
static int static_var;
public int public_var;
private void private_method(){}
static void static_method(){}
public void public_method(){}
}
class Son extends Father{
private int private_var;
static int static_var;
public int public_var;
private void private_method(){}
static void static_method(){}
}
以上代码中,子类Son和父类Father具有同名的变量和方法.对于以下代码,引用变量f声明为Father类型,实际引用的是Son的实例,那么通过变量f来访问成员变量和方法,绑定关系如下:
Father f=new Son();
int v1=f.private_var; //bind with father's private_var
int v2=f.static_var; //bind with father's static_var
int v3=f.public_var; //bind with father's public_var
f.private_method(); //bind with father's private_method
f.static_method(); //bind with father's static_method
f.public_method(); //bind with son's public_method
我个人的理解是方正就是把子类强制转换成父类对象,这样当你有多个不同的继承自父类的子类时,实际用的时候用的方法和变量都会是各自对应的子类
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |