您的位置:首页 > 职场人生

黑马程序员——面向对象-多态

2015-03-03 15:39 232 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
 
    这个多态的图片要小很多,应该可以有很好的效果。
 



果然清晰明了!!!
 
多态的小例子:
abstract class Animal {
abstract void eat();

}

class Dog extends Animal {
void eat() {
System.out.println("啃骨头");
}

void lookHome() {
System.out.println("看家");
}
}

class Cat extends Animal {
void eat() {
System.out.println("吃鱼");
}

void catchMouse() {
System.out.println("抓老鼠");
}
}

class Pig extends Animal {
void eat() {
System.out.println("饲料");
}

void gongDi() {
System.out.println("拱地");
}
}

class DuoTaiDemo {
public static void main(String[] args) {

// Cat c = new Cat();
// c.eat();
// c.catchMouse();

Animal a = new Cat(); // 自动类型提升,猫对象提升了动物类型。但是特有功能无法s访问。
// 作用就是限制对特有功能的访问。
// 专业讲:向上转型。将子类型隐藏。就不用使用子类的特有方法。

// a.eat();

// 如果还想用具体动物猫的特有功能。
// 你可以将该对象进行向下转型。
// Cat c = (Cat)a;//向下转型的目的是为了使用子类中的特有方法。
// c.eat();
// c.catchMouse();

// 注意:对于转型,自始自终都是子类对象在做着类型的变化。
// Animal a1 = new Dog();
// Cat c1 = (Cat)a1;//ClassCastException

/*
* Cat c = new Cat();
*
* // Dog d = new Dog();
*
* // c.eat(); method(c); // method(d); // method(new Pig());
*/

method(new Dog());

}

public static void method(Animal a)// Animal a = new Dog();
{
a.eat();

if (a instanceof Cat)// instanceof:用于判断对象的具体类型。只能用于引用数据类型判断
// //通常在向下转型前用于健壮性的判断。

{
Cat c = (Cat) a;
c.catchMouse();
} else if (a instanceof Dog) {
Dog d = (Dog) a;
d.lookHome();
} else {

}

}
/*
* public static void method(Cat c) { c.eat(); } public static void
* method(Dog d) {
* }
*/
}


示例(毕老师和毕姥爷的故事):
/*
毕老师和毕姥爷的故事。
*/

class 毕姥爷 {
void 讲课() {
System.out.println("管理");
}

void 钓鱼() {
System.out.println("钓鱼");
}
}

class 毕老师 extends 毕姥爷 {
void 讲课() {
System.out.println("Java");
}

void 看电影() {
System.out.println("看电影");
}
}

class DuoTaiDemo2 {
public static void main(String[] args) {
// 毕老师 x = new 毕老师();
// x.讲课();
// x.看电影();

毕姥爷 x = new 毕老师();
x.讲课();
x.钓鱼();

毕老师 y = (毕老师) x;// ClassCastException
y.看电影();

}
}


多态下成员(成员变量、成员函数、静态成员函数)的特点:                         *一定要弄明白这个*
class Fu {
int num = 3;
void show() {
System.out.println("fu show");
}

static void method() {
System.out.println("fu static method");
}
}

class Zi extends Fu {
int num = 4;
void show() {
System.out.println("zi show");
}

static void method() {
System.out.println("zi static method");
}
}

class DuoTaiDemo3 {
public static void main(String[] args) {
Fu.method();
Zi.method();
Fu f = new Zi();//
f.method();
f.show();
System.out.println(f.num);

Zi z = new Zi();
System.out.println(z.num);
}
}


 
 
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: