How a subclass which extends a superclass calls the builder of parent class
I have a parent class like
class A{
//Constructors only called by builder.
public static class builder{
//builder code.
}
}
Class B Extends ClassA{
//constrctor
}
Now if i do in my test
final classA dempClassA = new ClassB("pa开发者_开发技巧rameters here");
how can i call the builder now..?
Sorry guys the builder is a class...My mistake.
If I understand well what you're trying to say, you have the following situation:
public class ClassA {
// Constructors only called by builder.
public static class Builder {
// builder code.
public static void hello() {
System.out.println("Hello");
}
public void hello1() {
System.out.println("Hello1");
}
}
}
And you access it this way:
class ClassB extends ClassA {
public static void main(String[] args) {
ClassA.Builder.hello();
ClassA.Builder builder = new Builder();
builder.hello1();
}
}
If you want to call that method from outside the A
class then it shouldn't be private.
If you just want it to be part of the B
creation process then you should do something like this:
class B extends A {
public B() {
super(); // invokes A's constructor
}
}
class A {
public A(){
// use builder() here
}
}
Make ClassA's builder
method protected
(rather than private
), so they're visible to ClassB, then use an anonymous class to call it, like this:
ClassA tempClassA = new ClassB("parameters here") {
{
// This block is called during construction
builder();
}
};
Since the builder
(is that a class btw? or is the return type missing?) is static, you'd call it like A.builder()
. And for it to be visible, you shouldn't make it private :)
Edit: since it is a class, you have several possibilities:
- if you need a new instance call
new A.builder(...)
- if builder provides static methods (in which case the question would be why this is a class) call
A.builder.someStaticMethod(...)
精彩评论