以下是我的代码,其中一个称为汽车(基类)的类,由福特和本田(子类)继承。在主类(不是汽车)中,我通过福特和本田打印可变汽车,它们继承了汽车类的汽车。我面临的问题是,如果汽车设置为任何负数,它不会显示此 IllegalaArgumentException。
public class car{
protected long cars;
public void setCars(long number) {
if(cars < 0)
throw new IllegalArgumentException("cars must be ≥ 0!");
cars = number ;
}
}
public class honda extends car{
public String toString(){
String st = "HONDA" + "no of cars : " + cars ;
return st;
}
}
public class main{
public static void main(String[] args){
car[] cscar = new car[10];
for(int i = 0; i < 10; i++ ){
cscar[0] = new honda(-100);
}
}
}
最佳答案
目前尚不清楚您面临哪个问题,但似乎您希望实现 IllegalArgumentException
当汽车数量为负数时在子类中抛出。
所以这应该有效:
函数
setCars
应该稍微改变一下:当前您将汽车数量设置为负数,然后抛出异常。相反,您应该在设置之前检查该号码:public void setCars(long number) { if(cars < 0) throw new IllegalArgumentException("cars must be ≥ 0!"); cars = number ; }
我假设
cars
是基类中的变量。所以它应该是私有(private)的,并且只能通过汽车类中的任何位置的setCars
函数进行设置。切勿直接设置它:public class Car { private long cars; // ... }
子类要么根本不覆盖
setCars
,要么(如果需要覆盖)首先调用父方法:public class Honda { // setCars function is not overwritten here, // so parent function will be called } public class Ford { // setCars function is overwritten here, // but parent function is called first: @Override public void setCars(long number) { super.setCars(number); // if we've got here, then exception was not thrown // so function can do something else } }
或者,您可以将父函数设置为public final void setCars
,这样就没有人可以覆盖它
上面的代码将产生所需的结果:
Honda honda = new Honda();
honda.setCars(-5); // will throw the exception
关于java - 通过基类传递的变量未给出其父类的 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672449/