Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why does extending need an empty constructor?

I have classes SearchToUser and getFilesToWord. GetFilesToWord must inherit SearchToUser fields. Extending works if an empty construction in SearchToUser-class, otherwise:

cannot find symbol
symbol  : constructor SearchToUser()
location: class SearchToUser
public class GetFilesToWord extends SearchToUser{
       ^
1 error
make: *** [all] Error 1

I cannot understand why the empty constructor is required for extending.

[Added]

-- ALERT ERRR! USE COMPOSITION! Left as an "bad" example -- Composition VS Inheritance

It works but can you spot some weaknesses? Could I make the searchTerm private, create public method for it, create object of SearchToUser for the parameter in GetFilesToWord?

SearchToUser.java

public class SearchToUser {
   public static GetFilesToWord geader;
   public static String searchTerm;

   SearchToUser(String s){
       searchTerm=s.trim().toLowerCase();
       files=geader.getFilesToWord(s);
   }
   ...
}

GetFilesToWord.java

public class GetFilesToWord extends SearhToUser{
    public GetFilesToWord(){super(SearchToUser.searchTerm){
    ...
}
like image 863
hhh Avatar asked Dec 03 '22 05:12

hhh


1 Answers

The superclass doesn't need an empty constructor specifically. The subclass simply needs to call a constructor in the superclass. If the superclass has a public or protected no-arg constructor, this is called automatically, otherwise you need to be explicit.

Default constructor

public class Super {
}

public class Sub extends Super {
}

Here, Super specifies no constructor so one is added. Same for Sub. The above really looks like this:

public class Super {
  public Super() {
  }
}

public class Sub extends Super {
  public Sub() {
    super();
  }
}

Explicit no-arg constructor

public class Super {
  public Super() {
  }
}

public class Sub extends Super {
}

This is legal. A constructor is added to Sub that calls Super's default constructor.

Explicit constructor with arguments

public class Super {
  public Super(int i) {
  }
}

public class Sub extends Super {
}

This is a compile error like you have. Because Super has a constructor, no no-arg constructor is added automatically by the compiler. The way to deal with this is:

public class Super {
  public Super(int i) {
  }
}

public class Sub extends Super {
  public Sub() {
    super(0); // <-- explicit constructor call
  }
}
like image 133
cletus Avatar answered Dec 04 '22 19:12

cletus