有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有办法让一个不在超类中的方法访问超类的实例变量?

我有一个变量'ticking',它的初始值为'0'。当车辆移动或转向不同位置时,压力增加。假定Traffic类能够访问“ticking”变量,并确定它是红灯还是绿灯。我无法在Traffic类中访问滴答声,我不确定Traffic类中车辆的“扩展”(继承)是否可取。如果我继承了,那么我可以通过“getTicking”方法访问变量。但对我来说,在交通类中扩展它是没有意义的

超类:

public class Vehicle
{

    private String location;
    private double speed;
    private double weight;
    private double moving = 0;
    private double road = 5;
    private double ticking = 0;

    public Vehicle(String location, double speed, double weight)
    {
        this.location = location;
        this.speed = speed;
        this.weight = weight;
    }

    public String getLocation()
    {
        return location;
    }

    public void move()
    {
        if(moving == road)
        {
            System.out.println("Can't move any further.");
        }
        else
        {
            moving++;
            ticking++;
        }
    }

    public double moveQuantity()
    {
        return moving;
    }

    public void detectEnd()
    {
        if(moving == road)
        {
            System.out.println("You've reached the end of the road: " + moving + " miles");

        }
        else
        {
            System.out.println("You have not reached the end of the road.");
        }
    }

    public void changeLocation(String location)
    {
        this.location = location;
        ticking++;
    }

    public double getTicking()
    {
        return ticking;
    }


}

一个子类:

public class Car extends Vehicle
{
    String color;
    String dir;

    public Car(String location, double speed, double weight, String color)
    {
        super(location, speed, weight);
        this.color = color;
    }

    public void direction(String dir)
    {
        this.dir = dir;
    }


    public boolean canCarMove()
    {
        if(super.getLocation() == dir)
        {
            return true;
        }
        else
        {
            return false;
        }

    }



}

A类:

public class Traffic
{
    private double time;

    public Traffic(double time)
    {
        this.time = time;
    }

    public double ticking()
    {
        
    }
}

司机:

public class Driver
{
    public static void main(String [] args)
    {
        Car obj = new Car("North", 25 , 125, "blue");

        obj.direction("South");
        System.out.println(obj.canCarMove());

        obj.direction("North");
        System.out.println(obj.canCarMove());

        obj.move();
        obj.move();

        System.out.println(obj.moveQuantity());

        obj.move();
        obj.move();
        obj.move();
        obj.move();
        obj.detectEnd();


    }


}

共 (0) 个答案