13,勉強します
2943 ワード
パラメーターはすべてPet種類のサブクラスですが、feed(Pet pet)を使ってすべてのペットに対する餌やりを実現できますか?
多形を使って考えを実現する親タイプ を作成します.子類、子類書き換え親類方法 運転時は親タイプ、サブタイプのオブジェクトPet pet=new Dg(); 親類を方法として使用して多形を実現します.
多形を使って考えを実現する
public class Master {
//
public void feed( Pet pet ) {
pet.eat();
}
}
Pet pet = new Dog();
Master master = new Master();
master.feed( pet );// ,
練習問題の例public abstract class MotoVehicle {
private String no;//
private String brand;//
abstract int calRent(int days);//
public MotoVehicle()
{
}
public MotoVehicle(String no, String brand)
{
this.no = no;
this.brand = brand;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
public class Car extends MotoVehicle{
public Car(String no, String brand)
{
super(no,brand);
}
@Override
int calRent(int days) {
if(getBrand().equals(" "))
{
return 500 * days;
}
else
{
return 600 * days;
}
}
}
public class Kache extends MotoVehicle {
private int dunwei;//
public Kache(int dunwei)
{
this.dunwei = dunwei;
}
@Override
int calRent(int days) {
return 50*dunwei*days;
}
}
多形ではない実現方式Car[] cars = new Car[3];
cars[0] = new Car(" A12345"," ");
cars[1] = new Car(" B22222"," ");
cars[2] = new Car(" A62222"," ");
Kache[] kaches = new Kache[2];
kaches[0] = new Kache(1);//150
kaches[1] = new Kache(4);//600
int total = 0;
for(int i = 0; i < cars.length; i++)
{
total += cars[i].calRent(3);
}
for(int i = 0; i < kaches.length; i++)
{
total += kaches[i].calRent(3);
}
System.out.println(" " + total);//5850
多形を使って実現MotoVehicle[] motoVehicles = new MotoVehicle[5];
motoVehicles[0] = new Car(" A12345"," ");
motoVehicles[1] = new Car(" B22222"," ");
motoVehicles[2] = new Car(" A62222"," ");
motoVehicles[3] = new Kache(1);
motoVehicles[4] = new Kache(4);
int total = 0;
for(int i = 0; i < motoVehicles.length; i++)
{
total += motoVehicles[i].calRent(3);
}
System.out.println(" " + total);
豆ジョンリンク:https://www.jianshu.com/p/3bacbcb9bdec 出所:著作権は著者の所有になります.商業転載は作者に連絡して授権を獲得してください.商業転載ではないので、出典を明記してください.