简体   繁体   English

如何直接访问m1()方法中的A类变量?

[英]How can i access Class A variable in m1() method directly?

class A {
    int i = 10;
}

class B extends A {
    int i = 20;
}

public class C extends B{
    int i = 30;

    public static void main(String[] args) {
        C c = new C();
        c.m1();
    }

    public void m1() {
        System.out.println(i);       // 30
        System.out.println(super.i); // 20
    }
}

I have a class A , which contains a default variable. 我有一个A类,它包含一个默认变量。 I created a child class B which extends class A and one more child class C which extends class B . 我创建延伸类A和延伸类B中的一个或多个子类别C的子类B.

I want to access class A variable in child class C m1() method. 我想访问子类C m1()方法中的A类变量。 Is there any direct way to access it? 有没有直接访问它的方法?

change this line 改变这一行

System.out.println(super.i); // 20

to

System.out.println(((A)this).i);

To complicate your life try this: 为了使你的生活复杂化,试试这个:

public void m1() {
    System.out.println(this.i);
    C c = new C();
    Class<? extends Object> cls = c.getClass().getSuperclass().getSuperclass();
    Field[] fields = cls.getDeclaredFields();
    for ( Field field : fields )
    {
        String in = field.getName();
        int iv = field.get((Object)c);
        System.out.println(iv);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在以下程序中访问此m1()方法? - How can I access this m1() method in the following program? 我如何从不同的 class 方法访问变量 - How can i access the variable from different class method 如何从内部类方法访问局部变量? - How can I access to local variable from inner class method? 在Java中,我如何在另一个班级中直接更改另一个班级的按钮和字符串 - In java how can I directly change another class' buttons and strings while I'm in another class 如何在方法外部访问已在其他类中实例化的类A的成员变量? - How can I access the member variable of class A outside the method, that has been instantiated in other class? 我无法访问类的方法 - I'm not able able access the method of class 如何访问“未命名”类的方法? - How can I access a method of an “unnamed” class? 如何直接从另一个类访问变量(即不使用类名或对象)? - How to access variable from another class directly(i.e. without using class name or object)? 当我可以直接使用类名访问唯一的静态方法时,创建一个 Spring bean 是否有利 - Is it advantageous to create a Spring bean when I can access the only static method directly with class name 如果我已将其声明为Java中类的成员变量,是否可以访问另一个方法中一个方法的变量值? - Can i access the value of a variable of one method in another method if i have declared it as a member variable of the class in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM