Java entity - why do I need an empty constructor?

后端 未结 8 859
情歌与酒
情歌与酒 2020-12-08 07:23

This might sound stupid to you, but why do I need to define an empty constructor in my @Entitys?

Every tutorial I saw said : every entity needs an empty

8条回答
  •  鱼传尺愫
    2020-12-08 07:41

    All the answers are fine.

    But let's talk with code. Following snippets of code will give you more clarity.

    PersonWithImplicitConstructor.java

    public class PersonWithImplicitConstructor {
        
        private int id;
        
        private String name;
    
    }
    

    First we have to compile the .java file

    javac PersonWithImplicitConstructor.java

    Then class file will be generated.

    Running the javap on top this class file will give you the following information.

    javap PersonWithImplicitConstructor.class

    Compiled from "PersonWithImplicitConstructor.java"
    public class PersonWithImplicitConstructor {
      public PersonWithImplicitConstructor();
    }
    

    NOTE: If you want more information, you can use -p flag on javap.

    The next java file will have parameterised constructor only.

    PersonWithExplicitConstructor.java

    public class PersonWithExplicitConstructor {
        
        private int id;
        
        private String name;
    
        public PersonWithExplicitConstructor(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
    

    javac PersonWithExplicitConstructor.java

    javap PersonWithExplicitConstructor.class

    Compiled from "PersonWithExplicitConstructor.java"
    public class PersonWithExplicitConstructor {
      public PersonWithExplicitConstructor(int, java.lang.String);
    }
    

    PersonWithBothConstructors.java

    public class PersonWithBothConstructors {
    
        private int id;
        
        private String name;
    
        public PersonWithBothConstructors() {
    
        }
    
        public PersonWithBothConstructors(int id, String name) {
            this.id = id;
            this.name = name;
        }
        
    }
    

    javac PersonWithBothConstructors.java

    javap PersonWithBothConstructors.class

    Compiled from "PersonWithBothConstructors.java"
    public class PersonWithBothConstructors {
      public PersonWithBothConstructors();
      public PersonWithBothConstructors(int, java.lang.String);
    }
    

提交回复
热议问题