如何从抽象类中获取类的变量?

时间:2021-09-22 23:29:59

if I have an abstract class and a class that extends it, how can I get variable of the class that extends it to the class that is extended, something like this:

如果我有一个抽象类和一个扩展它的类,我怎样才能获得将它扩展到扩展类的类的变量,如下所示:

abstract class A {
    void getVariable () {
        //get *variable* from class B and print it out
    }
}

class B extends A {
    int variable = 5;
}

3 个解决方案

#1


3  

You cannot access variable field from child class directly but you can do like this

您无法直接从子类访问变量字段,但您可以这样做

abstract class A {
   abstract int getVariable ();

   void anotherMethod() {

       System.out.println("Variable from child: " + getVariable());
   }
}

class B extends A {
    int variable = 5;

    @Override
    int getVariable() {
        return variable;
    }
}

#2


0  

Forget about variables: What you might inherit and override is behaviours (=methods). Try this:

忘掉变量:你可以继承和覆盖的是行为(=方法)。试试这个:

abstract class A {
    protected abstract int getVariable ();
}

class B extends A {
    private int variable = 5;
    protected int getVariable ()
    {
        return variable;
    }
}   

class C extends A {
    protected int getVariable ()
    {
        return 0; // This class might decide not to define its own variable.
    }
}

#3


0  

variable is only known to class B. Its superclass A has no knowledge of it. If you move variable to the superclass A and don't mark it private, then you can access it from B.

变量只有B类知道。它的超类A不知道它。如果将变量移动到超类A并且不将其标记为私有,则可以从B访问它。

#1


3  

You cannot access variable field from child class directly but you can do like this

您无法直接从子类访问变量字段,但您可以这样做

abstract class A {
   abstract int getVariable ();

   void anotherMethod() {

       System.out.println("Variable from child: " + getVariable());
   }
}

class B extends A {
    int variable = 5;

    @Override
    int getVariable() {
        return variable;
    }
}

#2


0  

Forget about variables: What you might inherit and override is behaviours (=methods). Try this:

忘掉变量:你可以继承和覆盖的是行为(=方法)。试试这个:

abstract class A {
    protected abstract int getVariable ();
}

class B extends A {
    private int variable = 5;
    protected int getVariable ()
    {
        return variable;
    }
}   

class C extends A {
    protected int getVariable ()
    {
        return 0; // This class might decide not to define its own variable.
    }
}

#3


0  

variable is only known to class B. Its superclass A has no knowledge of it. If you move variable to the superclass A and don't mark it private, then you can access it from B.

变量只有B类知道。它的超类A不知道它。如果将变量移动到超类A并且不将其标记为私有,则可以从B访问它。