Java中可扩展性的实现

Java中可扩展性的实现

在JAVA中程序的可扩展性的实现有两种,通过代码举例如下:

一、将基类类型作为参数类型,使用instanceof判断传入实参引用的所属类型,从而决定该执行那部分代码

public class TestSimpleExtend {
public static void main(String[] args) {
TestSimpleExtend test = new TestSimpleExtend();
Animal animal = new Animal("animalName");
Cat cat = new Cat("catName","yellow");
Dog dog = new Dog("dogNmae","black");

test.method(animal);
test.method(cat);
test.method(dog);
}

public void method(Animal obj) {
System.out.println("The animal's name is:" + obj.name);
if(obj instanceof Cat) {
Cat c = (Cat) obj;
System.out.println("and its eyesColor is:" + c.eyesColor);
}
if(obj instanceof Dog) {
Dog d = (Dog) obj;
System.out.println("and its furlColor is:" + d.furlColor);
}
}
}

class Animal {
String name;

//one-arg constructor
Animal(String name){
this.name = name;
}
}

class Cat extends Animal {
String eyesColor;

//two-args constructor
Cat(String name,String eyesColor) {
super(name);
this.eyesColor = eyesColor;
}
}

class Dog extends Animal {
String furlColor;

//two-args constructor
Dog(String name,String furlColor) {
super(name);
this.furlColor = furlColor;
}
}

二、使用“动态绑定”机制,它是面向对象思想最核心的机制,能够实现的可扩展性也最优。

使用“多态”有3点要求:1、要有继承; 2、要用方法覆盖; 3、基类引用指向子类的对象。

public class TestPolymoph {
public static void main(String[] args) {
Animal a = new Animal("animal");
Cat c = new Cat("catName","yellow");
Dog d = new Dog("dogNmae","black");

Lady ly1 = new Lady("Miss.",a);
Lady ly2 = new Lady("Mr.",c);
Lady ly3 = new Lady("Mrs.",d);

ly1.myPetEnjoy();
ly2.myPetEnjoy();
ly3.myPetEnjoy();
}
}

class Lady {
private String name;
private Animal pet;

Lady(String name,Animal pet){
this.name = name;
this.pet = pet;
}

public void myPetEnjoy() {
pet.enjoy();
}
}
class Animal {
String name;

//one-arg constructor
Animal(String name){
this.name = name;
}

public void enjoy(){
System.out.println("叫....");
}
}

class Cat extends Animal {
String furlColor;

//two-args constructor
Cat(String name,String furlColor) {
super(name);
this.furlColor = furlColor;
}

public void enjoy(){
System.out.println("猫叫....");
}
}

class Dog extends Animal {
String furlColor;

//two-args constructor
Dog(String name,String furlColor) {
super(name);
this.furlColor = furlColor;
}

public void enjoy(){
System.out.println("狗叫....");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值