gpt4 book ai didi

java - 为什么我的继承申请不起作用?

转载 作者:行者123 更新时间:2023-12-01 06:51:36 27 4
gpt4 key购买 nike

我正在做一份过去的学校作业,它是关于带有子类“时钟”的微波应用程序。不知何故,我对我的代码感到困惑并完全迷失了方向。有人可以帮我解决这些问题吗?谢谢!

enter image description here

首先是 Clock 类。

class Clock extends Microwave {

private int hour;
private int minute;
private int second;

Clock()
{
hour = 0;
minute = 0;
second = 0;
}

Clock(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}

public int getHour()
{
return hour;
}

public int getMin()
{
return minute;
}

public int getSec()
{
return second;
}

public String toString()
{
return (String.valueOf(second));
}

protected void tick()
{
second++;

if(hour == 23 && minute == 59 && second == 59)
{
hour = 0;
minute = 0;
second = 0;
} else if(minute == 59 && second == 59)
{
hour++;
minute = 0;
second = 0;
} else if(second == 59)
{
minute++;
second = 0;
}
}
}

接下来是父类 Microwave。

class Microwave {

private int maxPower;
private int currentPower;
private Clock theClock;

Microwave()
{
maxPower = 500;
currentPower = 500;
theClock = new Clock();
}

Microwave(int maxp, Clock theClock)
{
maxPower = maxp;
currentPower = maxPower;
theClock = new Clock();
}

public int getCurrentPower()
{
return currentPower;
}

public int getMaxPower()
{
return maxPower;
}

public String getTime()
{
return "The time is " + theClock.getHour() + ":" + theClock.getMin() + ":" + theClock.getSec();
}

protected void cook(int p, int t)
{
if(p < maxPower)
{
currentPower = p;
} else
{
System.exit(0);
}

for(int i = 0; i < t; i++)
{
theClock.tick();
}
}
}

最后是主方法类。

class TestMicrowave
{
public static void main(String []args)
{
Clock c = new Clock(14, 30,30);
Microwave m = new Microwave(750, c);
System.out.println("The microwave is currently at " +
m.getCurrentPower() + " watts and "+ m.getTime());


m.cook(600,45); // should advance time to 14:31:15

System.out.println(m.getTime());

m.cook(800,45); // shoudln't cook as power > maxPower
System.out.println(m.getTime());

}
}

我认为,Microwave 类中的 getTime() 方法有问题,但我不知道它出了什么问题。提前致谢!

最佳答案

时钟不是子类。微波炉由时钟组成。从 Clock 类中删除“扩展微波”。

此设计中不应该有任何继承。

关于java - 为什么我的继承申请不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25169363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com