[Java] polymorphism

Polymorphism

What is polymorphism?

It refers to the variety of forms of things.
For example: the cat is an animal. The cat is a cat.
----------------------------------------------

Polymorphic prerequisite

Relations have inherited or implemented
to have a method overrides
have references to parent child class object
----------------------------- -----------------

Polymorphic member access features

Member variables: the compiler to see the parent class, run to see the parent class
member method: Compile see the parent class, subclass run to see
-------------------------- --------------------

Polymorphic benefits and drawbacks

Benefits: improve scalability and maintainability of the code
drawbacks: You can not use specific subclass members
------------------------------- ---------------

Polymorphic use scenario
as arguments and return values to the method used. You can improve the scalability of the code.
----------------------------------------------

Polymorphic:

main {
	Dog d = new Dog();
	method(d);

	Cat c = new Cat();
	method(c);
}
public static void method(Animal a) {
	a.eat();
}

Polymorphic transition

Upcast : parent subclass object reference
downcast : referenced by the parent type turn into a corresponding real subclass object
format:

目标对象类型 对象名 = (目标对象类型) 被转换的引用

Note : Be sure to ensure that the same type of conversion. Otherwise it may cause abnormal type conversion: ClasCatException

Keywords : instanceof
reference for determining whether the left is the object of the right type

main {
	Animal a = new Dog();

	Dog d = new Dog();
	method(d);

	Cat c = new Cat();
	method(c);
}
public static void method(Animal a) {
	a.eat();

	if(a instanceof Dog) {
		Dog d = (Dog)a;
		d.lookHome();
	}else if (a instanceof Cat) {
		Cat c = (Cat)a;
		c.catchMouse();
	}
}
Published 38 original articles · won praise 4 · Views 817

Guess you like

Origin blog.csdn.net/Hide111/article/details/105035992