Java Foundation 6 - Inheritance and Polymorphism

1. Inheritance

A superclass is a collection of public properties and methods of the subclass. In addition to inheriting all the functions of the superclass, the subclass can also modify the inheritance or add new properties and methods. Inheritance is also an abstraction, which improves the reusability of classes, creates relationships between classes (the basis of polymorphism), and reduces the workload of coding and maintenance.

In addition to the inheritance relationship between classes and classes, objects and objects, there are relationships such as composition. Inheritance expresses affiliation "is a (is-a)", while composition expresses the containment relationship "has-a" by placing objects of an existing class into a new class.

[classModifier] class ClassName extends SuperClassName
{
	// class body
}

Notice:

(1) Inheritance models the "is a" relationship, don't blindly extend a class in order to obtain the functionality of other classes.

(2) Java only supports single inheritance, that is, a subclass can only directly inherit a superclass. Multiple inheritance can easily bring security risks, such as when multiple parent classes have the same method name but different content. But multi-level inheritance is supported.

2. Method overriding and super

(1) Method rewriting

Although the subclass inherits the functions of the parent class, sometimes it is necessary to modify the algorithm or add or cancel functions. At this time, try not to modify the source code. If you modify more than one place, the program that calls it must also be modified. In order to improve the extensibility of the program, this function needs to be rewritten in the parent class.

When the signature and return value type of the method of the subclass and the method of the superclass are the same, the method of the superclass is overridden. When overriding the method with the same name in the parent class, use super.method name(<parameter>);. Add the override annotation @Override before a class, and then you must override the parent class method, otherwise the compiler will report an error.

Notice:

①When the subclass overrides the parent class, it must be ensured that the subclass permission is greater than the parent class permission, otherwise a compilation error will occur. Private methods in the parent class cannot be accessed outside the class, so they cannot be overridden.

②The abstract method in the parent class must be overridden, otherwise the subclass is also an abstract class. Static methods can be inherited, but cannot be overridden. If the static method in the parent class is redefined by the subclass, the hidden static method is called through <parent class name>.<static method name>. Final methods cannot be overridden either (class inheritance breaks encapsulation, and final avoids classes and methods from being inherited and overridden).

(2) Hiding of attributes

When a subclass declares the same member variable name as the superclass, but can be of a different type, variables inherited from the superclass will be hidden. When a subclass performs operations inherited from the superclass, it handles variables inherited from the superclass, and when a subclass operates its own declared methods, it manipulates its own variables. Use "super.property" in methods declared in this class to access properties inherited from the superclass.

(3) Call the constructor of the parent class

The constructor of the parent class will not be inherited by the subclass, and can only be called using the keyword super in the constructor of the subclass. super() must be placed in the first line of the subclass constructor. If it is not explicitly called, super() is automatically used as the first sentence of the subclass constructor. Start execution from the constructor of the farthest superclass Object class, and finally execute other statements when the body of the constructor is executed, because the subclass first refers to the superclass initialization action.

It is best to provide a no-argument constructor for each class, otherwise the constructor must be explicitly specified in its subclasses.

When a constructor in a subclass calls other constructors in the subclass through this, at least one function in the subclass accesses super. This and super cannot appear at the same time, because they both have to write the first line, and the initialization action must be done first.

For constructors, initialize the object's state with as few actions as possible, and if you can avoid it, don't call any methods. If the method is polymorphic and is overridden, there will be potential problems, and only final and private methods can be safely called.

3. Polymorphism

Polymorphism means that in the case of inheritance, the objects of the superclass and its subclasses can respond to messages with the same name (override), but the specific implementation methods are different; the reference of the parent class or interface points to the object of its subclass. Polymorphism improves program scalability.

Object o=new Circle();//Type promotion, upcast
o.toString();//o which toString() is called is determined by the actual type of o, which is called dynamic binding
Circle c=(Circle)o;//Downcast, force the parent class reference to be converted to the subclass type

The characteristics of non-static method members in polymorphism: at compile time, see whether there is a method called in the class to which the reference variable belongs, if not, the compilation fails; at runtime, see whether there is a method called in the class to which the object belongs, when the object is created from starting with the class of , and looking up the class hierarchy, stopping as soon as an implementation is found. Simply put, compile to the left and run to the right.

(限面试)成员变量和静态方法的特点:无论编译运行,都参考左边,引用型变量所属类。静态方法与对象无关,静态区只有类名调用。而非静态方法存储在方法区的非静态区,非静态区方法被对象所引用

引用变量的类型转换,将引用转换为另一类型的引用,并不改变对象本身的类型。只能被转为:任何一个直接或间接超类的类型或实现的接口(向上转型,一般隐式转换),引用所指的对象的类型(唯一向下转型)。当一个引用被转换为其超类引用后,通过它能够访问的只有超类中声明的方法。需要访问子类中的方法,必须转型为子类的引用。

类型比较运算符instanceof,比较某个对象是否属于某个类型。o instanceof Circle相当于if(this.getClass()!=o.getClass()) return flase;。

4、Object类

Object类处在类层次的最高点,是所有类的直接或间接的超类,包含所有Java类都具有的属性和行为。当一个类没有指定继承性,它的父类默认是Object类,构造函数第一句的super()即为Object()。Object类不是抽象类,因为如果抽象,子类必须强制实现其中的所有抽象方法,使类的实现更复杂。

public String toString()返回该对象的字符串表示。默认返回该对象所属类名+该对象用十六进制表示的哈希码getClass().getName()+”@”+Integer.toHexString(hashCode());。(getClass()在Object类中,返回此对象运行时的类;用Class类描述所有类的共同特征,其中getName()返回此Class对象所表示的类的名称)通常被覆盖,返回该对象的描述性字符串。

boolean equals(Object obj)通过==比较两引用是否指向同一对象,即内存地址是否相同。通常该方法会被重写,用来判断两对象是否具有相同内容。

class Demo //extends Object
{
	private int num;

	Demo(int num)
	{
		this.num=num;
	}

	public boolean equals(Object obj)
	//复写Object类中的equals方法,参数必须是Object类,不然是重载
	{
		//return this.num==obj.num//编译失败,obj类中没有num变量
		if(!(obj instanceof Demo))//obj是否是Demo类型
			return false;
		Demo d=(Demo)obj;//向下转型
		return num==d.num;
	}
}

class Person
{
}

class ObjectDemo
{
	public static void main(String[] args) 
	{
		Demo d1=new Demo(2);
		Demo d2=new Demo(2);
		Person p=new Person();

		System.out.println(d1.equals(d2));//true
		System.out.println(d1.equals(p));//false,抛出异常更确切
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891997&siteId=291194637
Recommended