![](/img/trans.png)
[英]In Java, how do I override the class type of a variable in an inherited class?
[英]How do I override the variable that was given a value to in another class which has been inherited
我试图让用户输入超级类中汽车的座位数,但是要创建一种方法来打印子类“汽车”中的座位数。 但是,当我声明存储用户输入的变量时,出现错误,指出该变量不可见,这是因为它在另一个类中。
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 + ".");
}
}
如果要将变量设为私有,可以使用父类的公共函数getNoOfSeats()。
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + super.getNoOfSeats() + " seats.");
}
}
或者只是将变量noOfSeats更改为受保护或受包保护的变量,
noOfSeats是该类的私有成员,任何其他类都无法访问。 如果要使它可以从继承的类访问,请使其对说明符的访问权限为protected。
基于OOP概念,您甚至不能在子类中访问课外的私有变量。
在这里您声明
private int noOfSeats;
并且您尝试在子类的类外部访问它,这超出了私有变量范围。
要在子类中访问它,请使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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.