JAVA中类与对象的使用
实验代码
CD.java
package lab2;
public class CD {
int size;
int content[];
public void setSize(int size) {
this.size = size;
content = new int[size];
}
public int getSize() {
return size;
}
public int[] getContent() {
return content;
}
public void setContent(int[] b) {
int min = Math.min(content.length, b.length);
for (int i = 0; i < min; i++) {
content[i] = b[i];
}
}
}
Computer.java
package lab2;
public class Computer {
int data[];
CD includeCD;
public void putCD(CD cd){
includeCD=cd;
int size=includeCD.getSize();
data=new int[size];
}
void copyToComputer(){
int []b=includeCD.getContent();
int min= Math.min(data.length,b.length);
for (int i=0;i<min;i++){
data[i]=b[i];
}
}
public void addData(int m){
for (int i=0;i<data.length;i++){
data[i]=data[i]+m;
}
}
public void copyToCD(){
includeCD.setContent(data);
}
void showData(){
for (int i=0;i<data.length;i++){
System.out.printf("%3d",data[i]);
}
}
}
User.java
package lab2;
public class User {
public static void main(String[] args) {
CD dataCD = new CD();
int b[] = {1, 2, 3, 4, 5, 6, 7, 8};
dataCD.setSize(b.length);
dataCD.setContent(b);
int a[] = dataCD.getContent();
System.out.println("dataCD上的内容:");
for (int i = 0; i < a.length; i++) {
System.out.printf("%3d", a[i]);
}
Computer computerIMB = new Computer();
computerIMB.putCD(dataCD);
System.out.println("\n将dataCD的数据复制到计算机:computerIMB.");
computerIMB.copyToComputer();
System.out.println("computerIMB上的内容:");
computerIMB.showData();
int m = 12;
System.out.println("\ncomputerIMB将每个数据增加:" + m);
computerIMB.addData(m);
System.out.println("computerIMB函数增值后的数据复制到CD:dataCD");
computerIMB.copyToCD();
System.out.println("dataCD上的内容:");
a = dataCD.getContent();
for (int i = 0; i < a.length; i++) {
System.out.printf("%3d", a[i]);
}
}
}