Misconception: In Java, students don’t realize that methods are inherited, but constructors are not.

  • When students understand that a child class can call methods and constructors from their parent class they sometimes incorrectly conclude that constructors are also inherited.
  • For example students may understand the following code:
    • public class TheParentClass {
          String myName;
          public void parentMethod(){
              this.myName = "bob";
          }
      }
      public class TheChildClass extends TheParentClass {
          public static void main(String[] args) {
              TheChildClass obj = new TheChildClass();
              obj.parentMethod(); // Calls parent method!
          }
      }
  • However, they may write the following incorrect code, which assumes that the constructor written in TheParentClass is not inherited.
    • public class TheParentClass {
          String myName;
          public TheParentClass(String s){
              this.myName = s;
          }
      }
      public class TheChildClass extends TheParentClass {
          public static void main(String[] args) {
              // The following code doesn't compile!
              TheChildClass obj = new TheChildClass("alice");
          }
      }

More about this tip

External Source

Interview with Krishnendu Roy.