What is the difference between having a class as f

2019-03-14 19:37发布

问题:

What exactly is the difference between a final class and having a class constructor as private.

I know both can't be subclassed(correct me if i am wrong). Is their any difference?

回答1:

A final class cannot be extended. It prevents this

final class FinalClass {

}

// and later

class ExtendedClass extends FinalClass { // ERROR

}

This is useful for things like String - you wouldn't want someone to be able to overwrite the logic of String, one of the most commonly used Objects, and be able to, oh I don't know, add networking and send all the strings back you use. It's possible to do if you can extend String.

A private constructor cannot be called outside the class.

class PrivateCons {

    private PrivateCons() {

    }
}

// later
PrivateCons pc = new PrivateCons(); // ERROR

Often this ends up working like this: (java.lang.Math is a good example)

class FuncLib {
    private FuncLib() { } // prevent instantiation
    public static void someFunc(...) { }
    public static int anotherFunc(...) { }
}

Or it ends up working like this // Integer does this actually

class VerySpecial {

    private static Map<String,VerySpecial> cache;

    public static VerySpecial generate(String data) {
        VerySpecial result = cache.get(data);
        if(result == null) {
            result = new VerySpecial(data);
            cache.put(data,result);
        }
        return result;
    }

    private String data;

    private VerySpecial() { }

    private VerySpecial(String data) { this.data = data}

}

When you extend a class, your constructor by default attempts to call the default (no argument) constructor. If that is private, then you must explicitly call a non-private constructor when you extend it. If you have no non-private constructors to call you won't be able to extend it. Thanks for comments for pointing this out. :-)



回答2:

Instantiation

  • You can't instantiate a class with a private constructor. But you can use it as an utility class with static methods.
  • A final class can be instantiated but not extended, obviously you cant extend a class with a private constructor either as the implicit super() call would fail.

Look at the Math class it has a private constructor, can't be instantiated yet it has many static methods which are very helpful



回答3:

If you don't want your class to be sub-classed, then you use final. If you don't want other classes to instantiate your class, but rather you want to control how the object is constructed and maintained, you use private constructor.



回答4:

Having only private constructors is stronger than having a final class.

In detail: Having only private constructors in a class A strongly influences object creation. Usually you are then using a factory method. You can still create instances of A without a factory method using tricks, such as clone() or invoking the private constructor reflectively. But subclassing is not possible, because a subclass' constructor needs to be able to call super(). That would only be possible within a nested class inside A.

Having only private constructors often makes sense, e.g. to control instantiations via factory methods, e.g. for singeltons (see Effective Java item 3). But even in that case, I don't see a reason to not writing "final class", if just for documentation, so that readers immediately grasp that subclassing is not allowed.



回答5:

private members can be accessed by inner classes.

public class Outer {
  private Outer() {
    System.out.println("Outer()");
  }

  static class Inner extends Outer {
    {
      System.out.println("Inner()");
    }
  }

  public static void main(String... args) {
    new Inner();
  }
}

prints

Outer()
Inner()

A final class cannot be extended, but its constructor can be public. A private constructor can be called from another constructor or used by an inner class.



回答6:

A final class/method can never be inherited/overridden and will throw compilation error where as A class with private constructor will also throw compilation that'There is no default constructor is available for your class' and once u add a non final constructor and call it from your child class, There will be no error.

A private constructor is useful in case of creating singleton class(Only one instance of a class can exist),Where you make your constructor private and a variable to store single instance,which will be exposed with public static method. for ex.

public class Singleton{    
private static final Singleton instance = new Singleton();

//private constructor to avoid client applications to use constructor
private Singleton(){}

public static Singleton getInstance(){
    return instance;
}}

And for example String class in java is a final class.