Say I have the following class structure:
public class A{
A(int a){
...
}
}
abstract class B extends A{
}
public class C extends B{
C(int a){
super(a);
}
}
This code isn't valid in the sense that myMethod will not call A's constructor. Is there a way to do this?
What I ultimately want to do, is add functionality to a set of classes without affecting their functionality. All these classes currently extend a common class (runtimeException), so I was thinking of adding an intermediary abstract class.
(edit: the code in C shouldn't be a method, it was meant to be a constructor)
You will not be able to declare class B
like you wrote. To create an instance of B
you'll need to call A
constructor:
public abstract class B extends A {
public B() {
super(10); //or other number
}
}
public class C extends B {
public C(int a) {
super();
}
}
In other words, you always call constructor of "previous level", whether the class is abstract or not.
In order to avoid this strange number 10
I wrote and missing int
parameter of C
constructor, I suggest adding to child class constructor at least all parameters parent class constructor requires for any extends
pair of classes.
What I've seen commonly is a pattern like this:
public class A{
A(int a){
...
}
}
abstract class B extends A{
B(int a) {// "proxy" constructor"
super(a);
}
}
public class C extends B{
C(int a) {
super(a);
}
void myMethod(int a){
// super(a); <- note this is invalid code, you can only call this from the constructor
new C(0); // <-- this is valid
}
}
Granted, it's a bit verbose and boilerplate-y, but it allows you to avoid duplicating any functionality
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.