How to properly call a method in an abstract class

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{

{

Hi guys, I need help if you call the getInfo () and displayInfo () methods in all three classes below. I tried:

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

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

I also tried:

@Override
public void getInfo() {

}

but if I leave it empty nothing will happen. Basically, I'm trying to call a method in an abstract class in a simple way, without introducing it into each class.

Can someone please help me! Thanks in advance.

+4
source share
3 answers

, , , , , overriden . :

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);
  }
}

id, , foo .

, final, .

+3

, overridable ; overridable -, (== null).

+1

You should not call overriding functions inside the constructor. check link

0
source

Source: https://habr.com/ru/post/1619486/


All Articles