Reputation: 11499
Code:
ClassA extends ClassBase {
protected IntefaceA parA;
.... }
InterfaceA extends InterfaceBase
ClassBase {
protected IntefaceBase parB;
public method1() {
parB.someMethod();
}
Code:
ClassA testClass=new ClassA();
testClass.setParA(new InterfaceA {....}; );
testClass.method1();
I receive null pointer exception because method metho1 uses class variable from ClassBase that used by method1 is parB. Does it possible have method1 use parA? If not, I need copy&paste all code of method1 from base class to descendant.
Thanks.
Upvotes: 2
Views: 93
Reputation: 421290
You can't override fields in Java, i.e. you can't say, parA
overrides parB
in the way a method of a sub class would override a method of a base class.
What you need to do is to provide an access method, getPar
for the parB
variable, which you in ClassA
override to return parA
.
Then in method1
, when you need to access parA
you simply go through this method. Since all methods in Java are virtual the subclasses' getPar
method will be invoked, even if called from within ClassBase
.
interface InterfaceBase {
void someMethod();
}
interface InterfaceA extends InterfaceBase {
...
}
class ClassA extends ClassBase {
protected InterfaceA parA;
@Override
protected InterfaceA getPar() {
return parA;
}
}
class ClassBase {
protected InterfaceBase parB;
public void method1() {
InterfaceBase parObj = getPar().someMethod();
// Big method... no need for code duplication.
}
protected InterfaceBase getPar() {
return parB;
}
}
Upvotes: 2
Reputation: 116306
Overriding fields is not possible in Java, only overriding methods. So what you can do is hide your parA
/ parB
members behind a protected virtual
getter, and access them only via the getter method. Then override the getter in ClassA
to return parA
instead of parB
:
ClassBase {
private IntefaceBase parB;
protected IntefaceBase getPar() {
return parB;
}
public method1() {
getPar().someMethod();
}
}
ClassA extends ClassBase {
private IntefaceA parA;
protected IntefaceBase getPar() {
return parA;
}
}
Upvotes: 1