How do I call one constructor from another in Java?

前端 未结 21 2396
不知归路
不知归路 2020-11-22 01:06

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if th

21条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 01:29

    Pretty simple

    public class SomeClass{
    
        private int number;
        private String someString;
    
        public SomeClass(){
            number = 0;
            someString = new String();
        }
    
        public SomeClass(int number){
            this(); //set the class to 0
            this.setNumber(number); 
        }
    
        public SomeClass(int number, String someString){
            this(number); //call public SomeClass( int number )
            this.setString(someString);
        }
    
        public void setNumber(int number){
            this.number = number;
        }
        public void setString(String someString){
            this.someString = someString;
        }
        //.... add some accessors
    }
    

    now here is some small extra credit:

    public SomeOtherClass extends SomeClass {
        public SomeOtherClass(int number, String someString){
             super(number, someString); //calls public SomeClass(int number, String someString)
        }
        //.... Some other code.
    }
    

    Hope this helps.

提交回复
热议问题