Home > Java > javaTutorial > body text

Java concept understanding summary of polymorphism

WBOY
Release: 2022-09-01 14:48:01
forward
1725 people have browsed it

This article brings you relevant knowledge about java. It mainly talks about the detailed explanation of polymorphism in Java. The inheritance relationship enables a subclass to inherit the characteristics of the parent class and add some New features. A subclass is a specialization of its parent class. Each instance of a subclass is an instance of its parent class, but the reverse is not true. I hope it will be helpful to everyone.

Java concept understanding summary of polymorphism

Recommended study: "java Video Tutorial"

1. The concept of polymorphism

The inheritance relationship makes A subclass can inherit the characteristics of the parent class and add some new characteristics. A subclass is a specialization of its parent class, and every instance of a subclass is an instance of its parent class, but the reverse is not true. For example: every circle is a geometric object, but not every geometric object is a circle. Therefore, you can always pass an instance of a subclass to a parameter that requires a parent type. The reference case is as follows:

public class PolymorphismDemo{
/** Main method */
public static void main(String[] args){
  displayObject(new Circle(1,"red",false));
  displayObject(new Rectangle(1,1,"black",true));
}
 
public static void displayObject(GeometriicObject object){
  System.out.println("Created on "+ object.getDateCreated()+".Color is"+object.getColor());
}
}
Copy after login

Created on Mon Mar 09 19:25:20 EDT 2011.Color is red

Created on Mon Mar 09 19:25:20 EDT 2011.Color is black

The method displayObject has a parameter of type GeometricObject. displayObject can be called by passing any instance of GeometricObject. Objects of subclasses can be used wherever objects of parent class are used. This is commonly referred to as polymorphism. Simply put, Polymorphism means that variables of the parent type can refer to objects of the subtype .

2. Characteristics of polymorphism

The premise of polymorphism: inheritance (that is, there must be a child-parent class relationship.) When calling a method using a polymorphic parent class reference variable, it will be called Method overridden by subclasses. Definition format: parent class type variable name = new subclass type (); # #3. instanceof operator

Instanceof is a keyword of Java. Each letter in a Java keyword is

lowercase

.

In order to better understand type conversion, they can be thought of as similar to the relationship between animals, polar bears, and pandas. The animal class Animal is the parent class of the polar bear class Polar bear and the panda class Panda class. Polar bears are animals, so you can always safely assign an instance of Polar bear to an Animal variable. The usage of this keyword is to determine whether an object belongs to a certain data type

, and the return value is of Boolean type.

 
        Fu Zz=new Xu();
        Fu Zzz=new yiting();
        if(f1 instanceof Xu){
            System.out.println("Zz是Xu的类型");
        }
        else{
            System.out.println("Zzz是yiting的类型");
        }
Copy after login
4. Polymorphic transformation

1. Upward transformation

You can always convert an instance of a subclass into a variable of a parent class, which is called

Upcast

, because an instance of a subclass is always an instance of its parent class.

Function:

Reduce some repetitive code. When instantiating objects, you can instantiate different objects according to different needs

package project2;
	class Animal{
		int num=100;
		void say(){
			System.out.println("It's an Animal.");
		}
	}
 
	class Cat extends Animal{
		int num=50;
		void say(){
			System.out.println("It's a Cat.");
		}	
		void bark(){
			System.out.println("喵喵喵!");
		}
	}
 
	public class project2{
		public static void main(String[] args) {
			Animal cat=new Cat();//向上转型	
			System.out.println(cat.num);
			cat.say();
//			cat.bark();
		}
	}
Copy after login

Running results:

100

It's a Cat.


Do not force transformation when upcasting. The method pointed to or called by the parent class reference is the method of the subclass. This is called dynamic binding. After upward transformation, the parent class reference cannot call the subclass's own methods.

2. Downward transformation

Convert an instance of a parent class into its subclass variable. You must use conversion markers (subclass names) to perform explicit conversions to indicate your intentions to the compiler. For the conversion to be successful, you must ensure that the object being converted is an instance of the subclass.

Function:

When upcasting, other methods unique to subclass objects will be lost; you can cast down and then back again.

package project2;
class Animal{
	int num=100;
	void say(){
		System.out.println("It's an Animal.");
	}
}
 
class Cat extends Animal{
	int num=50;
	void say(){
		System.out.println("It's a Cat.");
	}	
	void bark(){
		System.out.println("喵喵喵!");
	}
}
 
public class project2{
	public static void main(String[] args) {
		Animal cat=new Cat();//向上转型
		Cat cat2=(Cat) cat;//向下转型
		System.out.println(cat2.num);
		cat2.say();
		cat2.bark();
	}
}
Copy after login

Run result:

50

It's a Cat.
Meow Meow Meow!



5. Method rewriting

Tip: To override a method, you need to define the method in the subclass with the same signature as the parent class.

Subclasses inherit methods from parent classes. Sometimes, a subclass needs to modify the implementation of a method defined in the parent class. This is called method overriding.

The following points are worth noting:

The overridden method must have the same signature as the overridden method, and the same or compatible return type. Compatibility means that the return type of an overriding method can be a subtype of the return type of the overridden method. It can be overridden only if the instance method is accessible. If the method defined in the subclass is private in the parent class, then these two methods have no relationship at all. Like instance methods, static methods can also be inherited. However, static methods cannot be overridden. If a static method defined in the parent class is redefined in the child class, the static method defined in the parent class will be hidden. Hidden static methods can be called using the syntax "parent class name.static method name". Prevent inheritance and overwriting

一个被final修饰的类和方法都不能被继承。被final修饰的数据域是一个常数。

有时候,可能希望防止类被继承。在这种情况下,使用final修饰符表明一个类是最终类,是不能作为父类的。Math类就是一个最终类。String、StringBuilder和StringBuffer类以及所有基本数据类型的包装类也都是最终类。例如,如下类A 就是最终类,不能被继承:

public final class A{
  //Data fields,constructors, and methods omitted
}
Copy after login

也可以定义一个方法为最终,最终方法不能被它的子类重写。例如如下,不能被重写:

public class Test {
  //Data fields,constructors, and methods omitted
 
  public final void m() {
    // Do something
 }
}
Copy after login

注:修饰符public、protected、private、static、abstract以及final可以用在类和类的成员上,只有final修饰符还可以用在方法中的局部变量上。方法内的final局部变量就是常量。

六、小结

为了重写一个方法,必须使用与它的父类中的方法一样的签名、一样或者兼容的返回类型来定义子类中的方法。实例方法只有在可访问时才能重写。这样,私有方法是不能重写的,因为它是不能在类本身之外访问的。如果子类中定义的方法在父类中是私有的,那么这两个方法是完全没有关系的噢!静态方法与实例方法一样可以继承。但是,静态方法不能重写,如果父类中定义的静态方法在子类中重新定义,那么父类中定义的方法被隐藏。可以使用表达式obj instanceof AClass 测试一个对象是否是一个类的实例。可以使用final修饰符来表明一个类是最终类,是不能被继承的;也可以表明一个方法是最终的,是不能被重写的。

推荐学习:《java视频教程

The above is the detailed content of Java concept understanding summary of polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template