简体   繁体   English

Java多态性/抽象类帮助

[英]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. 您正在使用两个int参数调用构造函数,但尚未创建此类构造函数。 You have only created a method named 'op' that takes two int arguments. 您仅创建了一个名为“ op”的方法,该方法带有两个int参数。

You would put the constructor in the "MultMath" class, like so: 您可以将构造函数放在“ MultMath”类中,如下所示:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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