我试图让用户输入超级类中汽车的座位数,但是提出了一种方法来打印子类“汽车”中的座位数。但是,当我声明存储用户输入的变量时,出现错误,指出该变量不可见,这是因为它在另一个类中。
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 + ".");
}
}
答案 0 :(得分:1)
如果要将变量设为私有,则可以使用父类的公共函数getNoOfSeats()。
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + super.getNoOfSeats() + " seats.");
}
}
或者只是将变量noOfSeats更改为受保护或受包保护,
答案 1 :(得分:0)
noOfSeats是该类的私有成员,任何其他类都无法访问。如果要使它可以从继承的类访问,请使其对说明符的访问权限为protected。
答案 2 :(得分:-1)
基于OOP概念,即使在子类中也不能访问类外的私有变量。
您在这里声明
private int noOfSeats;
然后您尝试在私有变量范围之外的child子类之外访问它。
要在子类中访问它,请设置noOfSeats变量
public int noOfSeats;
或
protected int noOfSeats;
在车辆类中。
如果要将noOfSeats变量设置为私有变量,请在车辆类(父类)上对public函数进行创建,然后从Car类(子类)中调用它。
您正在尝试访问
System.out.print("\nThe car has " + towingCapacity + ".")
Truck类中的towingCapacity变量,您没有在Vehicle类或Truck类中声明它。
因此,首先声明它,然后使用它。
有关java访问修饰符的更多详细信息,请阅读本文
https://www.softwaretestingmaterial.com/access-modifiers-in-java/