【发布时间】:2014-06-18 14:04:48
【问题描述】:
我得到了以下练习:
“鉴于这个类,
class Test {
int a;
Test(int a) {
this.a = a;
}
}
编写一个名为 swap() 的方法,用于交换两个 Test 对象引用所引用的对象的内容。”
我写了三个略有不同的练习示例:
示例 1
class Test {
public int a;
Test(int a) {
this.a = a;
}
public void swap(Test otherObject) {
int tempVar;
tempVar = this.a;
this.a = otherObject.a;
otherObject.a = tempVar;
}
}
class Chapter6_2c {
public static void main(String[] args) {
Test obj1 = new Test(1);
Test obj2 = new Test(2);
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
obj1.swap(obj2);
System.out.println("\nafter swap()\n");
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
}
}
示例 2
class Test {
public int a;
Test(int a) {
this.a = a;
}
public static void swap(Test objectOne, Test objectTwo) {
int tempVar;
tempVar = objectOne.a;
objectOne.a = objectTwo.a;
objectTwo.a = tempVar;
}
}
class Chapter6_2b {
public static void main(String[] args) {
Test obj1 = new Test(1);
Test obj2 = new Test(2);
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
Test.swap(obj1, obj2);
System.out.println("\nafter swap()\n");
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
}
}
示例 3
class Test {
int a;
Test(int a) {
this.a = a;
}
}
class Chapter6_2a {
public static void swap(Test objectOne, Test objectTwo) {
int tempVar;
tempVar = objectOne.a;
objectOne.a = objectTwo.a;
objectTwo.a = tempVar;
}
public static void main(String[] args) {
Test obj1 = new Test(1);
Test obj2 = new Test(2);
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
swap(obj1, obj2);
System.out.println("\nafter swap()\n");
System.out.println("obj1 has value " + obj1.a);
System.out.println("obj2 has value " + obj2.a);
}
}
在示例 1 和示例 2 中,swap() 方法被编写为 Test 类的成员,不同之处在于示例 2 中被定义为静态。在示例 3 中,swap() 方法是在 main() 方法中定义的。
我的问题是,从设计、开销和清晰度的角度来看,哪一种是定义 swap() 方法的最佳实践或最专业的方法?
我确实有一些想法,但我真的需要你的意见来确认它们是对还是错:
在示例 1 和示例 2 之间,我认为最好的方法是从开销的角度将 swap() 方法定义为静态(示例 2),因为类的静态成员不包含在该类的实例。我的假设正确吗?
从设计和清晰的角度来看,示例 3 不是定义 swap() 方法的好习惯,因为首先 swap() 方法与 Test 类非常相关,应该定义为它的成员和其次,一般来说,最好在密切相关的类中定义 main() 之外的所有方法。这个假设也正确吗?
提前感谢您抽出时间帮助我!!!
【问题讨论】: