gpt4 book ai didi

java - 继承不起作用

转载 作者:行者123 更新时间:2023-12-01 06:28:09 26 4
gpt4 key购买 nike

嘿,我刚刚练习继承,遇到了问题。我在我的汽车类(子类)中收到错误,车辆(父类)中的变量不可见。我没有做任何事情来改变这一点,我什至不知道如何让它隐形。谁能帮我解决这个问题。

public class Vehicle 
{
private String make, model, colour;
private int registrationNumber;

public Vehicle()
{
this.make = "";
this.model = "";
this.colour = "";
this.registrationNumber = 0;


}


public Vehicle(String make, String model, String colour,
int registrationNumber)
{
this.make = make;
this.model = model;
this.colour = colour;
this.registrationNumber = registrationNumber;
}


public String getMake()
{
return make;
}


public void setMake(String make)
{
this.make = make;
}


public String getModel()
{
return model;
}


public void setModel(String model)
{
this.model = model;
}


public String getColour()
{
return colour;
}


public void setColour(String colour)
{
this.colour = colour;
}


public int getRegistrationNumber()
{
return registrationNumber;
}


public void setRegistrationNumber(int registrationNumber)
{
this.registrationNumber = registrationNumber;
}



public String toString()
{
return "Vehicle [make=" + make + ", model=" + model + ", colour="
+ colour + ", registrationNumber=" + registrationNumber + "]";
}






}

public class Car extends Vehicle
{
private int doors;
private String shape;

public Car()
{
super();
this.doors = 0;
this.shape = "";
}

public Car(String make, String model, String colour, int registrationNumber)
{
super(make, model, colour, registrationNumber);
this.make = make;
this.model = model;
this.colour = colour;
this.registrationNumber = registrationNumber;


}






}

错误信息:

Description Resource    Path    Location    Type
The field Vehicle.make is not visible Car.java /VehicleApp/src line 19 Java Problem
The field Vehicle.model is not visible Car.java /VehicleApp/src line 20 Java Problem
The field Vehicle.colour is not visible Car.java /VehicleApp/src line 21 Java Problem
The field Vehicle.registrationNumber is not visible Car.java /VehicleApp/src line 22 Java Problem

最佳答案

“问题”是变量是私有(private),因此子类无法使用。据推测,您正在尝试直接在 Car 中访问它们(很难判断,因为您没有包含源代码)。

可以将它们设为 protected 变量 - 但我强烈建议您将它们保留为私有(private),而使用您的属性(get 和 set 方法)子类。字段是一个实现细节 - 您应该考虑向子类以及其他代码公开哪些API

有关 Java 中访问控制的更多详细信息,请参阅 JLS section 6.6 。例如:

Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

关于java - 继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12978827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com