Spn
Spn

Reputation: 450

Abstract method in a non abstract class

If we have for example :

class Person {
  // public void printInfos(){ }
}

class Student extends Person {
     public void printInfos(){
          System.out.println("studentInfos");
     }
}

class Teacher extends Person(){
     public void printInfos(){
          System.out.println("teacherInfos");
     }
}

main:
Person p1 = new Student();
Person p2 = new Teacher();

I want to write : p1.printInfos() and p2.printInfos() and print "studentInfos" & "teacherInfos" but I can't find a solution other than declaring an empty method inside the class Person (since we can't declare it as abstract and override it otherwise there will be no instanciation possible). I feel that the declaration of an empty method is wrong even if it works.

Upvotes: 0

Views: 912

Answers (2)

You should exactly declare Person as interface. Logically, Person shouldn't be instantiated. Defining new class and empty-bodied method are superfluous in this case.

If you insist on the gobbledygook approach, there is no sane way to do that other than defining new class.

interface Person {
   public void printInfos();
}

class Student implements Person {
     @Override
     public void printInfos(){
          System.out.println("studentInfos");
     }
}

class Teacher implements Person {
     @Override
     public void printInfos(){
          System.out.println("teacherInfos");
     }
}

main:
Person p1 = new Student();
Person p2 = new Teacher();

Upvotes: 2

MDaniluk
MDaniluk

Reputation: 62

Please tell me more about your needs for this class. Is there any good reason why you would want to create Person instance? If not it is clearly an abstract class for me and I think you should make it abstract.

You will still have option to declare constructor, some method that are "default" for the subclasses (an provide them an implementation) and make printInfos an abstract method.

abstract class Person {
    abstract void printInfos();
}

class Student extends Person {
    public void printInfos(){
        System.out.println("studentInfos");
    }
}

class Teacher extends Person{
public void printInfos(){
        System.out.println("teacherInfos");
        }
        }

Upvotes: 0

Related Questions