我正在尝试获取用户输入的 super 类中汽车的座位数,但创建一个方法来打印名为“Car”的子类中的座位数。但是,当我声明存储用户输入的变量时,我收到一条错误,指出该变量不可见,这是因为它位于另一个类中。
import java.util.Scanner;
class Vehicle {
Scanner s = new Scanner(System.in);
private String color;
private int noOfCylinders;
private int noOfSeats;
public Vehicle() {
color = "Black";
noOfCylinders = 0;
noOfSeats = 1;
}
public Vehicle(String color, int noOfCylinders, int noOfSeats) {
this.color = color;
this.noOfCylinders = noOfCylinders;
this.noOfSeats = noOfSeats;
}
public void getColor() {
System.out.print("Enter color of vehicle: ");
color = s.nextLine();
}
public String setColor() {
return color;
}
public void getNoOfCylinders() {
System.out.print("Enter number of cylinders: ");
noOfCylinders = s.nextInt();
}
public int setNoOfCylinders() {
return noOfCylinders;
}
public void getNoOfSeats() {
System.out.print("Enter numer of seats: ");
int noOfSeats = s.nextInt();
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders.";
return information;
}
}
public class CreateVehicle {
public static void main(String[] args) {
Car CarObject = new Car();
Truck TruckObject = new Truck();
CarObject.getColor();
CarObject.setColor();
CarObject.getNoOfCylinders();
CarObject.setNoOfCylinders();
CarObject.toString();
CarObject.getNumOfSeats();
TruckObject.getColor();
TruckObject.setColor();
TruckObject.getNoOfCylinders();
TruckObject.setNoOfCylinders();
TruckObject.toString();
System.out.print(("\nThe car ")+CarObject.toString());
System.out.print(("\nThe truck ")+TruckObject.toString());
}
}
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + noOfSeats + " seats.");
}
}
class Truck extends Vehicle {
public void printTowingCapacity() {
System.out.print("\nThe car has " + towingCapacity + ".");
}
}
最佳答案
如果您想将变量保持私有(private),可以使用父类的公共(public)函数 getNoOfSeats()。
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + super.getNoOfSeats() + " seats.");
}
}
或者只是将变量 noOfSeats 更改为 protected 或 package-protected,
关于java - 如何覆盖在另一个已继承的类中赋值的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57105474/