简体   繁体   中英

Java polymorphism/abstract class help

I'm trying to set parameters for a abstract class:

public abstract class NewMath {
    public abstract int op (int intOne, int intTwo);
}

Here is the extended subclass:

public class MultMath extends NewMath {
    public int op (int intOne, int intTwo){
        return intOne + intTwo;
    }
}

But when I try to instantiate an object while defining the parameters like this:

public class TestNewMath {
    public static void main(String [] _args) {
        MultMath multObj = new MultMath(3,5);
    }
}

It doesn't work. It gives me this error:

TestNewMath.java:3: cannot find symbol
symbol  : constructor AddMath(int,int)
location: class AddMath
        AddMath addObj = new AddMath(3, 5);

I know I'm missing something. What is it?

You're calling a constructor with two int arguments, but you haven't created such a constructor. You have only created a method named 'op' that takes two int arguments.

You would put the constructor in the "MultMath" class, like so:

public MultMath(int arg0, int arg1){

}

This would get rid of your compile error. Alternatively, you could do this:

public class TestNewMath {
  public static void main(String [] _args) {
    MultMath multObj = new MultMath();
     int x=1, y=2;
     multObj.op(x,y);        

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM