简体   繁体   中英

How to create class with no default constructor

I want to create a class like "android.view.View", a class that will show "There is no default constructor available in 'android.view.View'" error if super(...) is not called in class that extend my class, sorry for my bad english, is there anyone can help me? thanks

--edit

@Eran, thanks, your comment gives me a hint, so the culprit is Lombok annotation "@Data", it gives no error even I create a constructor with parameter, any idea how to achieve this with Lombok?

You can make it private so other classes can't use it.

public class MyClass{
    private String text;
    private int number;

    private MyClass(){
        this.text="hi";
    }

    public MyClass(int number){
        this();
        this.number = number
    }
    ...
}

In this way, child classes should use the non default constructor:

public MyChildClass1 extends MyClass{
    //NO COMPILE: No default constructor available in MyClass
}

public MyChildClass2 extends MyClass{
    public MyChildClass2(){
        //NO COMPILE: No default constructor available in MyClass
    }
}

public MyChildClass3 extends MyClass{
    public MyChildClass3(){
        super(); //NO COMPILE: MyClass() has private access
    }
}

public MyChildClass4 extends MyClass{
    public MyChildClass4(){
        super(2); //It Works! (it will initialize number=2 and text="hi")
    }
}

Here is your main class pattern.

public class MyParentClass {

    MyParentClass(int value) {

    }
}

If any class want to extend it without calling super(value) will get "There is no default contructor available in parent_class_name"

Like as below:

public class ChildClass extends MyParentClass {

}

I just provide the private constructor:

public class MyClass {
    private MyClass() {
        throw new UnsupportedOperationException();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM