java - 通过基类传递的变量未给出其父类的 IllegalArgumentException

标签 java

以下是我的代码,其中一个称为汽车(基类)的类,由福特和本田(子类)继承。在主类(不是汽车)中,我通过福特和本田打印可变汽车,它们继承了汽车类的汽车。我面临的问题是,如果汽车设置为任何负数,它不会显示此 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 当汽车数量为负数时在子类中抛出。

所以这应该有效:

  1. 函数setCars应该稍微改变一下:当前您将汽车数量设置为负数,然后抛出异常。相反,您应该在设置之前检查该号码:

    public void setCars(long number) {
        if(cars < 0)
            throw new IllegalArgumentException("cars must be ≥ 0!");
    
        cars = number ;
    }
    
  2. 我假设cars是基类中的变量。所以它应该是私有(private)的,并且只能通过汽车类中的任何位置的 setCars 函数进行设置。切勿直接设置它:

    public class Car {
    
        private long cars;
    
        // ...
    }
    
  3. 子类要么根本不覆盖 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/

相关文章:

java - 查询字符串由 Spring Framework 解码

java - 动态添加多个水平线性布局到选项卡

java - 如何使用 twitter4j 处理速率限制?

java - ColdFusion 程序员想要使用新版本的 Java APNS 但不知道如何编译 Java

java - 我应该如何通过 Struts 操作连接和使用我的核心类?

java - 在 Android 中将 ArrayList 对象添加到 GridView

java - 获取 selenium webdriver 类的 java.lang.NullPointerException

java - 计算平衡系数

java.lang.Object;无法转换为模型类 : error in Spring Boot

java - 无法在 spring-integration 4.1.x 中将 String 值转换为 ExpressionEvaluatingRequestHandlerAdvice 的表达式