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("狗叫....");
}
}