怎么访问超类的超类的成员变量

来源:百度知道 编辑:UC知道 时间:2024/07/07 12:41:26

给你举个例子吧:访问超类私有成员变量和非私有成员变量的方法是不同的,私有的需要通过反射,非私有的可以直接访问。
public class Clazz extends Father {

public static void main(String[] args) throws Exception {
Clazz zz = new Clazz();
String pub = zz.publicc;// 共有属性和方法直接访问
System.out.println(pub);
zz.pubMethod();

Class cla = Class.forName("com.bd.Father");
Method mes = cla.getDeclaredMethod("privMethod", new Class[] {});
mes.setAccessible(true);
mes.invoke(new Father());//访问私有方法
Field fie = cla.getDeclaredField("privatee");
fie.setAccessible(true);
String privatee = (String)fie.get(new Father());
System.out.print(privatee);//访问私有属性
}
}

class Father {
private String privatee = "私有属性";

public String publicc = "共有属性";

private void privMethod() {
System.out.println("私有方法");
}

public void pubMethod() {