java - 如何覆盖在另一个已继承的类中赋值的变量

标签 java class inheritance overriding superclass

我正在尝试获取用户输入的 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/

相关文章:

Javafx 表加载正确的行数,但加载重复的数据。我错过了什么吗?

c++ - 创建带有和不带有 new 关键字的 C++ 对象

C++父类方法调用

c# - MassTransit 消息消费者永远看不到子类类型

java - 对象变量可能尚未初始化

java - 如何更改 itext 中列表的字体大小和颜色?

java - MouseInfo.getPointerInfo() - 如何获取光标 View

java - 如何将 AWT 中的类导入到我的 Android 项目中?

C++与类中的成员相同的类

c# - 一种将基类型转换为派生类型的方法