第五章 继承、多态、抽象类与接口 课后训练(2)
训练 3 输出水果类价格
重写toString()方法,将如下信息输出到控制台上:红色的苹果被称为“糖心富士”,每500克4.98元,买了2500克“糖心富士”,需支付多少元。
public class fruit {
//声明变量
String name;
double prices;
public static void main(String[] args) {
//创建对象,赋予属性
fruit a = new fruit("糖心富士",4.98);
//重写toString后输出a
System.out.println(a);
}
//含参构造方法
public fruit(String name , double prices){
this.name = name;
this.prices = prices;
}
//重写toString方法,自定义输出
public String toString(){
return "红色的水果被称为" + name +" ,每500g" + prices + "元,买了2500g" + name + ",需支付多少元?";
}
}
训练 4 让猫狗是同类
重写equals()方法,得到一个荒唐的结果:猪和狗是同类。
public class animal {
int id;
String name;
public static void main(String[] args) {
animal a = new animal(1,"狗");
animal b = new animal(1,"猪");
System.out.println(a.name + "与"+b.name+"是否为一类");
System.out.println(a.equals(b));
}
//含参构造方法
public animal(int id, String name) {
this.id = id;
this.name = name;
}
//重写equals方法
public boolean equals(Object obj){
//判断传入的对象是否相等
if (this == obj) {
return true;
}
//判断传入的对象是否为空,或者两者类不不一样
if (obj == null || getClass() != obj.getClass()) {
return false;
}
// 直接返回true,不考虑id和name属性
return true;
}
}
原文地址:https://blog.csdn.net/qq_62387839/article/details/142426362
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!