多态测试:
代码:
package com.javaclass4;
public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();
parent=child;
parent.printValue();
parent.myValue++;
parent.printValue();
((Child)parent).myValue++;
parent.printValue();
}
}
class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
//super.printValue();
System.out.println("Child.printValue(),myValue="+myValue);
//System.out.println();
}
}
运行结果:
为什么会出现这种结果呢:这个实际就是多态的具体表现,当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。因为父类被子类赋予类型,所以父类.printValue()调用的是子类的方法,如果我想看父类的value值,则可以用super关键字来访问它,将注释取掉就很容易看清子类的value和父类value。
多态编程有两种主要形式: (1)继承多态(2)接口多态:
(1)代码:
public class Zoo
{
public static void main(String args[])
{
Feeder f = new Feeder("小李");
//饲养员小李喂养一只狮子
f.feedAnimal(new Lion());
//饲养员小李喂养十只猴子
for (int i = 0; i < 10; i++)
{
f.feedAnimal(new Monkey());
}
//饲养员小李喂养5只鸽子
for (int i = 0; i < 5; i++)
{
f.feedAnimal(new Pigeon());
}
}
}
class Feeder
{
public String name;
Feeder(String name)
{
this.name = name;
}
public void feedAnimal(Animal an)
{
an.eat();
}
}
abstract class Animal
{
public abstract void eat();
}
class Lion extends Animal
{
public void eat()
{
System.out.println("我不吃肉谁敢吃肉!");
}
}
class Monkey extends Animal
{
public void eat()
{
System.out.println("我什么都吃,尤其喜欢香蕉。");
}
}
class Pigeon extends Animal
{
public void eat()
{
System.out.println("我要减肥,所以每天只吃一点大米。");
}
}
狮子、猴子和鸽子都继承了Animals,所以当我们调用eat函数时,传入什么类型参数,则调用什么类型函数,这就是多态的表现:不同的对象可以执行相同的行为,但是他们都需要通过自己的实现方式来执行!
(2)代码:借鉴 https://blog.csdn.net/weixin_43133824/article/details/83787446 该博主的代码
由于java是单继承,所以在面对多个特性的时候,可以使用“接口(interface)”来抽象对象的行为特性。
Java中“接口”的语法特性:
1、定义一个接口,采用关键字interface,实现一个接口,采用关键字implements
2、接口的成员函数自动成为public的,数据成员自动成为 static和final的。
3、如果接口不声明为public的,则自动变为package。
4、一个类可以同时实现多个接口。
接口的使用:接口类型 接口类型的变量=new 实现了接口的具体类型()。
package data;
//创建一个food接口
interface food
{
public void getname();
public void eat();
}
//创建一个fruit接口,继承于food接口
interface fruit extends food
{
//此接口继承了父接口的方法
}
//创建一个meat接口,继承于food接口
interface meat extends food
{
//此接口继承了父接口的方法
}
//ora描述的是橘子,继承于fruit接口
class ora implements fruit
{
public void eat()
{
System.out.println("此方法是吃橘子的方法");
}
public void getname()
{
System.out.println("吃的水果名称为橘子");
}
}
//hotpot类描述的是羊肉,继承于meat接口
class hotpot implements meat
{
public void eat()
{
System.out.println("此方法是吃羊肉的方法");
}
public void getname()
{
System.out.println("吃的肉名称为羊肉");
}
}
//test类描述的是实现多态接口
public class test
{
public static void main(String[] args)
{
food f1=new ora();
f1.eat();
f1.getname();
food f2=new hotpot();
f2.eat();
f2.getname();
}
}
运行结果:
多态的好处:当你要修改程序并扩充系统时,你需要修改的地方较少,对其它部分代码的影响较小。