TEZZ
TEZZ

Reputation: 179

How to call a method in an abstract class properly

public abstract class Human{
    public String name;
    public int number

    public void getInfo(){
        Name = JOptionPane.showInputDialog("Please enter your name: ");
        money = Double.parseDouble(JOptionPane.showInputDialog("Please enter amount of money .00: "));
    }

    public void displayInfo(){
        JOptionPane.showMessageDialog(null,"Name: "+name+"\n"+
                                           "Number: "+number);
    }
}

public class Student extends Human {

}

public class Teacher extends Human{

}

public class Janitor extends Human{

{

I need help if calling the methods getInfo() and displayInfo() in all 3 classes below. I have tried:

public class Student extends Human{
    public Student(){
          getInfo();
          displayInfo();
    }

it works, but it generates a warning saying "problematic call in constructor" I guess it is not the best way to do it.

I also tried:

@Override
public void getInfo() {
    
}

but if I leave it empty nothing happens. Basically I am trying to call the method in the abstract class in a simple way without needing to type it up in every class.

Upvotes: 4

Views: 200

Answers (3)

Ivaylo Toskov
Ivaylo Toskov

Reputation: 4031

As already mentioned, you shouldn't call overridable methods in constructors, because if another class overrides this method and invokes the constructor of the superclass, it may try to use values that are not initialized yet, since the overriden method will be invoked. Example:

public class Superclass {
  protected int id;
  protected void foo() {
    System.out.println("Foo in superclass");
  }

  public Superclass() {
    foo();
  }
}

public class Subclass extends Superclass {
  public Subclass(int id) {
    super();
    this.id = id;
  }

  @Override
  protected void foo() {
    System.out.println("Id is " + id);
  }
}

This will print the unitialized value of id, since you first call the constructor of the superclass which invokes the foo method of the subclass.

You can fix this by making your methods final if this suits your case.

Upvotes: 3

sameera sy
sameera sy

Reputation: 1718

You shouldn't call overridable functions inside a constructor. check this link

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

You get the warning because it's a good practice not to call overridables in the constructor; since these overridables could try to access member variables that are not initialized yet (== null) .

Upvotes: 1

Related Questions