Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call abstract class method

I have an interface called Hospital.java

public interface Hospital {
    public void operate();
    public void doScan();
    public void doVaccination();
}

I have an abstract class called StreetHospital.java

public abstract class StreetHospital implements Hospital{
    public void operate(){
        System.out.println("Street Hospital operate");
  }
}

Now I am using another class CommunityHospital.java to extend StreetHospital.java

public class CommunityHospital extends StreetHospital{

    public void doScan(){
        System.out.println("CommunityHospital doScan");
    }
    public void doVaccination(){
        System.out.println("CommunityHospital doVaccination");
}
    public void operate(){
        System.out.println("CommunityHospital operate");
    }
}

I am creating the CommunityHospital object in my MainHospital class

public class MainHospital {

    public static void main(String[] args){
        CommunityHospital ch = new CommunityHospital();
        ch.operate();
        ch.doScan();
        ch.doVaccination();

    }
}

I am getting this output:

CommunityHospital operate
CommunityHospital doScan
CommunityHospital doVaccination

My question is how do I print "Street Hospital operate" sysout statement in output?

like image 728
nsd Avatar asked Dec 13 '22 23:12

nsd


2 Answers

You can't do that.

There can't be two methods in one class with same name and param. Once you override operate() in CommunityHospital , the same mthod in StreetHospital no longer exist.

like image 184
Mobility Avatar answered Dec 29 '22 08:12

Mobility


Add another function to CommunityHospital with another name say superOperate like this:

public void superOperate(){
    super.operate();
}

and call it from anywhere

like image 38
Yashar Aliabbasi Avatar answered Dec 29 '22 10:12

Yashar Aliabbasi