这两道题我个人感觉可以较直观的感受到构造函数及成员方法的使用
题目要求:
1.使用this调用已有的有参构造函数,width与length分别为5和6。
2.为Rectangle类覆盖toString
。按照width=实际宽度值,length=实际长度值
的格式输出
public Rectangle(){
this(5,6);
}
public Rectangle(int width, int length) {
this.width = width;
this.length = length;
}
public String toString(){
return "width="+width+",length="+length;
}
定义一个Person类,该类包括age,name两个数据成员和eat(),work()两个成员方法,并实现对两个数据成员的Getter方法。然后通过测试程序,实现相应对象的操作。程序输出结果如下:
请按提示完善相应的程序。(注意掌握成员方法及构造方法的调用)
class Person
{
public int age; //声明公共字段age
private String name; //声明私有字段name
public int getAge() { //实现age成员的Getter方法
return age;
}
public String getName() { //实现name成员的Getter方法
return name;
}
public void eat() //定义无参数的eat方法
{
System.out.println("会生活");
}
public void work(String s) //定义带参数的work方法
{
System.out.println("努力创造"+s);
}
public Person(int age, String name) //定义一个带参数构造函数
{
this.age = age;
this.name = name;
}
}
public class Main
{
public static void main(String[] args)
{
Person p = new Person(18, "张三");//调用类的有参构造函数
System.out.println("姓名:"+p.getName()+"\n年龄:" + p.getAge());
p.eat(); //调用对象的eat方法
p.work("美好生活");//
}
}