class access example

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85266319
// hiding/Lunch.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Demonstrates class access specifiers. Make a class
// effectively private with private constructors:

class Soup1 {
  private Soup1() {}

  public static Soup1 makeSoup() { // [1]
    return new Soup1();
  }
}

class Soup2 {
  private Soup2() {}

  private static Soup2 ps1 = new Soup2(); // [2]

  public static Soup2 access() {
    return ps1;
  }

  public void f() {}
}

// Only one public class allowed per file:
public class Lunch {
  void testPrivate() {
    // Can't do this! Private constructor:
    // - Soup1 soup = new Soup1();
  }

  void testStatic() {
    Soup1 soup = Soup1.makeSoup();
    System.out.println("soup:" + soup);
    System.out.println("Soup1.makeSoup():" + Soup1.makeSoup());
  }

  void testSingleton() {
    Soup2.access().f();
  }

  public static void main(String[] args) {
    new Lunch().testStatic();
  }
}
/* My Output:
soup:Soup1@6d06d69c
Soup1.makeSoup():Soup1@7852e922
*/

summary, there's one and only one Soup2, Soup1 has multiple instances.

references:

1. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/hiding/Lunch.java

2. On Java 8 - Bruce Eckel

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/85266319