我在大学里为初学者学习Java课程,我很困惑它是如何编译/执行的以下是代码:
public class Counter {
private int counter;
private int end;
public Counter(int start, int end) {
this.counter = start;
this.end = end;
}
public String toString() {
return "[Counter counter=" + counter + " end=" + end + "]";
}
public int getCounter() {
return counter;
}
public void count(int increment) {
if (counter < end) {
counter += increment;
}
}
public void count() {
count(1);
}
}
其他类
public class CounterProgram {
private Counter counter;
public void init() {
counter = new Counter(1, 3);
}
public void run() {
System.out.println(counter);
counter.count();
System.out.println(counter);
counter.count();
System.out.println(counter);
counter.count();
System.out.println(counter);
}
public static void main(String[] args) {
CounterProgram counterProgram = new CounterProgram();
counterProgram.init();
counterProgram.run();
}
}
我不确定count(1)
方法中的含义public void count
任何人都可以解释?谢谢你的时间!
count(1)
是参数1
( int
) 对 count
方法的调用:
public void count(int increment)
Counter
类中有两个count()
方法,每个方法都有不同的参数。其中之一是通用的;它可以将给定的增量值添加到内部counter
变量的值。另一个是具体的,因为它应该将counter
增加 1
.
因此,您的public void counter()
方法可以使用更通用的public void counter (int increment)
,通过调用它,而不是重新实现自己的逻辑。
换句话说,您的counter()
方法是调用counter (int increment)
以避免代码重复,这在高质量代码中非常重要。
count(1)
调用overloaded
方法count(int increment)
,如果计数器小于end
,则计数器值递增1。
如果你是Java新手,我建议考虑你的自我编译器。 如果您使用的是任何 IDE(如 NetBeans),或者可以在调试模式下运行。对于此代码:
- 首先
public static void main(String[] args)
因为每个程序都从 main 方法运行。 - 其次在右侧和侧面创建一个类
CounterProgram counterProgram = new CounterProgram();
的对象new CounterProgram();
调用类的构造函数,该构造函数为空,因为未定义 - 启动计数值的第三个
init
- 第四
run()
现在在运行方法中,您可以在页面上进行演示多个命令。它仅在条件<end
的情况下递增