super-constructor if there is no super class?

后端 未结 5 966
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 09:42

I found a class like this:

public class Computer implements Serializable {

        private static final long serialVersionUID = 1L;    

        //...
              


        
5条回答
  •  余生分开走
    2020-12-11 10:19

    By default all classes inherit java.lang.Object. So a hidden code in your class is

    public class Computer extends java.lang.Object implements Serializable {
    
            private static final long serialVersionUID = 1L;    
    
            //...
            public Computer() {
                super(); //here Object's default constructor is called
            }
            //...
    }
    

    If a parent class has default constructor (no argument) and if a child class defines a default constructor, then an explicit call to parent's constructor is not necessary.

    Java does it implicitly, in other words, Java puts super() before first statement of the child's constructor

    consider this example

    class Base {
    
        public Base() {
            System.out.println("base");
        }
    }
    
    class Derived extends Base {
    
        public Derived() {
            //super(); call is not necessary.. Java code puts it here by default
            System.out.println("derived");
        }
    }
    

    So when you create Derived d = new Derived(); the output is..

    base
    derived
    

提交回复
热议问题