Why Can You Instantiate a Class within its Definition?

前端 未结 9 1822
无人共我
无人共我 2020-12-24 13:22

A coworker (who is very new to Java) stopped in today and asked what seemed like a very simple question. Unfortunately, I did an absolutely horrible job of trying to explain

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 13:49

    A Class is just a blue print that describes what each and every instance of the class will look like and behave like. Depending on the visibility of the class and its constructors, code in the same class, in the same package, or complete strangers may create instances.

    It is for example common to provide a factory method in classes where the constructor should not be public:

    public class Foo {
        // only I get to create new instances
        private Foo() {
        }
    
        // but you can get instances through this factory method
        public static Foo createFoo() {
            return new Foo();
        }
    }
    

提交回复
热议问题