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;
}
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;
}
}
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.
}
}
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.