Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

eclipse - Java -- private constructor vs final and more

Suppose there is a class with all of its constructors declared as private.

Eg.:

public class This {
    private This () { }

    public someMethod( ){
    // something here
    }
   // some more-- no other constructors
}

From what I know, making all constructors private is similar to declaring the class "This" as final-- so that it can't be extended.

However, the Eclipse messages i'm getting are giving me the impression that this is possible-- an all-constructors-private class can be extended. Take a look at this:

When I attempt to extend this class with something like

public class That extends This {
    ...
}

Eclipse giving me an error that: "Implicit super constructor This() is not visible for default constructor. Must define an explicit constructor."

When i define a constructor of its own:

public class That extends This {
    That () {..} 
    ...
}

this time i'm getting : "Implicit super constructor This() is not visible for default constructor. Must explicitly invoke another constructor."

Is there a way to get around this-- of extending a class of which all constructors are private?

if yes, how?

if no, what's the difference between stopping a class from being extended by i.) making its constructors private, and ii.) defining it as final?

Note: i saw Can a constructor in Java be private? among some other discussions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You declare a class final vs. make its constructor private for different reasons:

  • You make class final to indicate that the class is not designed for inheritance.
  • You make all constructors private to give the class the control over its instantiation.

In other words, using final controls inheritance, while using private constructors control instantiation.

Note that declaring constructors private disables inheritance only from the outside. Inside the class, you may still inherit it with a named or an anonymous derived class.

When you make all constructors of the class private you need a static method that is public to make the class usable. One common kind of the static method is factory method: you can let the users of your class call private constructors indirectly through a public static method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...