简体   繁体   English

无法访问数组Java中的对象

[英]Can't access object in the array java

else if (control.equals("Car") == true)
{
     owner = (scanner.nextLine());                     
     address = (scanner.nextLine());
     phone = (scanner.nextLine());
     email =(scanner.nextLine());
     convertible= (scanner.nextBoolean());
     color = (scanner.nextLine());

     vehicleLot[i] = new car(owner, address, phone, email, convertible, color);
     System.out.println(vehicleLot[i].getOwner());
     System.out.println(vehicleLot[i].getAddress());
     //System.out.println(vehicleLot[i].getColor());
}

The above code is in my main method. 上面的代码在我的主要方法中。 The line that is commented out throws out the error "cannot find symbol in the class vehicle". 被注释掉的行抛出错误“在类车辆中找不到符号”。 I am reading from a file and placing the information into the correct objects data fields. 我正在从文件中读取信息,并将信息放入正确的对象数据字段中。 The array is an array of vehicles. 该阵列是车辆的阵列。 From what I understand, an element of the array of vehicles can be a vehicle or any subclass of vehicle. 据我了解,车辆阵列中的一个元素可以是车辆或车辆的任何子类。 Getters and setters methods are available for each respective class with subclass using the getters and setters for the parents class. 对于使用父类的getter和setter的子类,每个相应的类都可以使用getter和setter方法。 Car is a subclass of vehicle. 汽车是汽车的子类。 Why is it not trying to access cars methods first before trying vehicle when I just created the car object? 为什么在刚创建car对象时,在尝试车辆之前不尝试首先访问car方法? Does the problem lie in my car constructor? 问题出在我的汽车制造商身上吗? car is static because it is a nested class and throws an error if you don't keep it static. car是静态的,因为它是一个嵌套类,如果不保持静态,则会引发错误。 Below is the summary of the car class. 以下是汽车课的摘要。

static class Car extends vehicle
{
  private boolean convertible;
  private String color;
  public Car()
  {

  }
  public Car(String ownersName, String address, String phone, String email, boolean convertible, String color)
  {
      super.setOwner(ownersName) ;
      super.setAddress(address);
      super.setPhone(phone);
      super.setEmail(email);
      this.convertible = convertible;
      this.color = color;
      System.out.println(this.convertible);
  }//Car class ends

The System.out.println prints out the correct value for that string, so I'm interested as to why the object wants to try and only use the class vehicle for its methods instead of class car and class vehicle. System.out.println为该字符串打印出正确的值,所以我对为什么对象想要尝试并且仅将class vehicle用于其方法而不是class car和class vehicle感兴趣。 Here is vehicle if that helps. 这是车辆,如果有帮助。

public static class Vehicle
{
    private String ownersName;
    private String address; 
    private String phone;
    private String email;

    public Vehicle()
    {
    }
    public Vehicle(String ownersName, String address, String phone, String email)
    {
        this.ownersName = ownersName;
        this.address = address;
        this.phone = phone;
        this.email = email;
     }
}//Vehicle class ends

If I understood the question, you are asking why the following line doesn't compile : 如果我理解这个问题,那么您在问为什么以下行无法编译:

System.out.println(vehicleLot[i].getColor());

vehicleLot is defined as an array of Vehicle . vehicleLot被定义为Vehicle的数组。 It can contain instances of any sub-classes of Vehicle . 它可以包含Vehicle任何子类的实例。 Therefore, vehicleLot[i] doesn't necessarily have a getColor() method, since that's a method of Car . 因此, vehicleLot[i]不一定具有getColor()方法,因为这是Car的方法。

In order to access the methods of Car you have to cast the Vehicle reference to Car : 为了访问Car的方法,您必须将Vehicle引用强制转换为Car:

System.out.println(((Car)vehicleLot[i]).getColor());

This, of course, would only work if vehicleLot[i] refers to a Car instance. 当然,只有在vehicleLot[i]引用Car实例的情况下, vehicleLot[i] If not, a ClassCastException will be thrown. 否则,将引发ClassCastException

It seems like you missed an intricate detail regarding polymorphism, you can put a Car Object into a Vehicle array(Due to Polymorphism) and on calling methods on the arrayElements the correct overloaded method is called (if you have overloaded it ie is ) , But since there is no getColor( ); 似乎您错过了有关多态性的复杂细节,可以将Car Object放入Vehicle数组(由于Polymorphism),并在arrayElements上调用方法时,将调用正确的重载方法(如果已重载,即is),但是因为没有getColor( ); in your Vehicle class it doesn't work , suppose you had written a getColor() in Vehicle Class and overloaded it in the Car class , 在您的Vehicle类中不起作用,假设您已经在Vehicle类中编写了getColor()并在Car类中对其进行了重载,

Then had you said 那你说过

Vehicle v=new Car(); 
v.getColor();

The Car's getColor() will be called , However ,Please Note that the Compiler first checks if the vehicle class has the method , only then it checks if the actual object type and calls the overloaded method belonging to the car class , But in your case the first test fails and an error is thrown Try Reading about P olymorphism and Run-time Binding in Java Car的getColor()将被调用,但是,请注意, 编译器首先检查车辆类是否具有方法 ,然后才检查实际对象类型并调用属于汽车类的重载方法,但是在您的情况下第一次测试失败并引发错误尝试阅读有关Java中的同态和运行时绑定的信息

"Car is a subclass of vehicle. Why is it not trying to access cars methods first before trying vehicle when I just created the car object?" “汽车是汽车的子类。为什么在我刚创建汽车对象时,在尝试汽车之前不先尝试访问汽车方法?”

This really only applies to polymorphic methods, those that are defined for a superclass, and then (possibly) overridden in a subclass. 这实际上仅适用于多态方法,即为超类定义的方法,然后(可能)在子类中重写。 If you say 如果你说

vehicle v;

the compiler knows only that v is a vehicle ; 编译器只知道vvehicle ; therefore, it can only access methods defined for the vehicle class. 因此,它只能访问为vehicle类别定义的方法。 If v is actually a car , and one of those methods is overridden for car , then it will call the method in car . 如果v实际上是car ,而其中的一种方法被car覆盖,则它将在car调用该方法。 But if you use a method that's defined only for car (not for vehicle ), the compiler won't allow it, because it only knows that v is a vehicle , and it doesn't know that it will have a car method such as getColor . 但是,如果使用仅为 car定义的方法(而不为vehicle定义的方法),则编译器将不允许它,因为它仅知道vvehicle ,并且不知道它将具有car方法,例如getColor This is true even if you have just assigned v to a new car . 即使您刚刚将v分配给new car The compiler looks only at the declaration vehicle v ; 编译器仅查看声明vehicle v it doesn't try to go backward through your program to figure out what you've assigned to it. 它不会尝试遍历您的程序来弄清楚您分配给它的内容。

You can solve the problem with a cast, as in Eran's answer, but in this particular case you don't need to. 您可以使用演员表来解决问题,就像Eran的回答一样,但是在这种情况下,您不需要这样做。 Change 更改

 vehicleLot[i] = new car(owner, address, phone, email, convertible, color);
 System.out.println(vehicleLot[i].getOwner());
 System.out.println(vehicleLot[i].getAddress());
 System.out.println(vehicleLot[i].getColor());

to

 car newCar = new car(owner, address, phone, email, convertible, color);
 vehicleLot[i] = newCar;
 System.out.println(newCar.getOwner());
 System.out.println(newCar.getAddress());
 System.out.println(newCar.getColor());

The compiler may think vehicleLot[i] can be any vehicle , but it knows that newCar is a car because you declared it that way. 编译器可能认为vehicleLot[i]可以是任何vehicle ,但它知道newCarcar因为您是这样声明的。

(By the way, the Java convention is for class names, like car and vehicle , to start with upper-case letters.) (顺便说一下,Java约定是将类名(例如carvehicle )以大写字母开头。)

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

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