这个程序怎么改

来源:百度知道 编辑:UC知道 时间:2024/05/16 02:09:04
package b;
public class apple
{
private String str;
public String getStr()
{
return str;
}
public void setStr(String str)
{
this.str = str;
}
public apple()
{
System.out.println("无参的构造器运行了");
}
public apple(String str)
{
System.out.println("有参的构造器运行了");
this.str = str;
}
}

import b.apple;
public class testApple
{
public static void main(String[] args)
{
apple a1 = new apple();
al.setStr("给私有的成员变量赋值");
String s1 = a1.getStr();
System.out.println(s1);
apple a2 = new apple("调用的是一个有参数的构造器");
String s2 = a2.getStr();
System.out.println(s2);
}
}
不能运行 引入包的地方 错误

这个程序是正确的啊,不过你就想表达什么呢,就只是锻炼下构造函数的作用是么?
我没试,但看起来是可以运行的

public class apple {
private String str;

public String getStr() {
return str;
}

public void setStr(String str) {
this.str = str;
}

public apple() {
System.out.println("无参的构造器运行了");
}

public apple(String str) {
System.out.println("有参的构造器运行了");
this.str = str;
}

public static void main(String[] args) {
apple a1=new apple();
a1.setStr("给私有的成员变量赋值");
System.out.println(a1.getStr());
apple a2=new apple("调用的是一个有参数的构造器");
System.out.println(a2.getStr());
}

}

拿去运行。