Default constructors in Java

前端 未结 7 1742
南旧
南旧 2020-12-09 07:21

I know I\'m asking some serious 101 question here...

I have some class Foo and a class Bar that extends Foo. In Foo

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 07:58

    If parameters are not required and/or have default values then you can define default constructor (without parameters):

    class Foo
    {
        public final int DEFAULT_A = 42;
        protected int a;
        protected int b;
    
        public Foo(final int a, final int b)
        {
            this.a = a;
            this.b = b;
        }
    
        // Is equal to new Foo(Foo.DEFAULT_A, 0);
        public Foo()
        {
            this.a = this.DEFAULT_A;
        }
    
    }
    
    class Bar extends Foo {}
    
    class PiBar extends Bar
    {
        public final int DEFAULT_A = Math.PI;
    
    }
    

提交回复
热议问题