Java basic self-study notes-Chapter eleven: inheritance and polymorphism

Chapter 11: Inheritance and Polymorphism

One. Parent category and sub category

1. Inheritance allows you to create a class (parent class), which can then be expanded into a more specific class (subclass)

public class Circle extends GeometricObject{
    
    }

Circle is a subclass, which can also be called a subclass, a derived class, and an extended class.
GeometricObject is the parent class and also becomes the base class. The superclass
extends is the inheritance keyword.

2. Attention

  • The subclass is not a subset of the parent class, and the subclass usually contains more information and methods than the parent class
  • Private member variables in the parent class are not accessible by the subclass, but can access public accessors and modifiers in the parent class
  • Either "is a kind" or inheritance relationship. For example, square is a kind of rectangle, but the square class cannot be used to extend the rectangle class, because width and height are not suitable for square
  • There must be a "is a" relationship between the parent class and the child class, but the inheritance relationship cannot be established blindly
  • Many inheritance is not allowed in java. A Java class can only directly inherit from one parent class, but multiple inheritance can be achieved through interfaces

Several classes derive a subclass called multiple inheritance

2. Use the super keyword

The keyword super refers to the parent class and can be used

  • Call the constructor in the parent class
super();//调用父类无参构造
super(参数);//调用有参构造
  • Call ordinary methods in the parent class

The use of super() or super(parameter) must appear in the first line of the subclass's construction method, which is the only way to explicitly call the parent class's construction method

public class GeometricObject {
    
    //定义父类
	private String color;//颜色
	private boolean filled;//是否填充

	public GeometricObject() {
    
    
		this("white", false);//调用重载的构造方法
	}

	public GeometricObject(String color, boolean filled) {
    
    
		this.color = color;//this调用对象引用的隐藏数据域
		this.filled = filled;
	}
}
public class Circle extends GeometricObject {
    
    //Circle类继承GeometricObject 类
	private double radius;
	public static final double PI = 3.14;

	public Circle() {
    
    
		this(1.0, "black", true);
	}

	public Circle(double radius, String color, boolean filled) {
    
    
		super(color, filled);//调用父类构造方法,必须放在第一行
		this.radius = radius;
	}
}

When constructing an instance of a class, the constructors of all parent classes along the inheritance chain will be called. When constructing an object of a subclass, the subclass construction method will first call the construction method of its parent before completing its task. If the parent class inherits from other classes, then the parent class's construction method will call its own parent class's construction method before completing its own task. This process continues until the last constructor along the inheritance architecture is called.

The following example is obtained by checking the data, which can better reflect the construction method chain

public class Faculty extends Employee{
    
    
    public Faculty(){
    
    
        System.out.println("(3)Performs Faculty's tasks") ;
    }
    public static void main(String[] args){
    
    
        Faculty fac=new Faculty();
    }
}
class Employee extends Person {
    
    
    public Employee(){
    
    
        System.out.println("(2)Performs Employee's tasks");
    }
}
class Person {
    
    
    public Person(){
    
    
        System.out.println("(1)Performs Person's tasks");
    }
}
//运行结果
//(1)Performs Person's tasks
//(2)Performs Employee's tasks
//(3)Performs Faculty's tasks

There is no explicit definition of the construction method in the subclass, the default no-parameter construction is implicitly called, and the no-parameter construction of the parent class is called by default, but the no-parameter construction is not defined in the parent class, so it cannot be compiled successfully

public class GeometricObject {
    
    
	private String color;
	private boolean filled;
	public GeometricObject(String color, boolean filled) {
    
    
		this.color = color;
		this.filled = filled;
	}
	//父类中没有定义无参构造
}

public class Circle extends GeometricObject {
    
    
	private double radius;
	public static final double PI = 3.14;
	//默认调用无参构造和父类的无参构造
}

Therefore: If you want to design a class that can be inherited, it is best to provide a no-parameter construction method to avoid programming errors

3. Method rewriting

1. To rewrite a method, it is necessary to define the method with the same signature and return value type as the parent class definition

public class GeometricObject {
    
    
	@Override
	public String toString() {
    
    //父类toString方法
		return "GeometricObject [color=" + color + ", filled=" + filled + "]";
	}
}

public class Circle extends GeometricObject {
    
    
	@Override//只有父类的实例方法是可访问时才能被覆盖
	public String toString() {
    
    //子类重写父类toString方法,方法签名和返回值类型相同
		return super.toString()+"  radius:"+getRadius();//重写方法必须使用super.方法名 调用父类的方法
	}
}

	public static void main(String[] args) {
    
    //测试
		// TODO Auto-generated method stub
        Circle circle2=new Circle(3.0,"black",true);
        System.out.println(circle2.toString());//GeometricObject [color=black, filled=true]  radius:3.0
	}

Similar to instance methods, static methods can also be inherited, but static methods cannot be overridden. If the static method redefined by the parent class is overridden in the subclass, then the static method in the parent class will be hidden

2. The difference between rewriting and reloading

**Overload: **The same method name and different signatures define multiple methods
**Override:** Provide a new implementation of the method in the subclass, the signature and return value type must be the same

Method overriding occurs in different classes that
are related due to inheritance Method overloading can occur in one class or in different classes that are related due to inheritance

Override annotation @Override
If the annotation is used but not overwritten, an error will be reported

In the overriding method, super.function() must be used to call the method of the parent class

3.
Object class All classes in java inherit from Object class

Four. Polymorphism

1. Polymorphism means that the variables of the parent class can point to the objects of the parent class

2. An instance of each subclass is an instance of its parent class, and vice versa

Five. Dynamic binding

1. Declare type and actual type

   Object o=new GeometricObject();
 //Object声明类型 GeometricObject实际类型

2. Dynamic binding means that it can be implemented in many parts of the inheritance chain

3. The declaration type of the reference variable determines which method is matched at compile time, and the actual type determines the implementation of the dynamic binding method

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		printString(new Circle(3.0));//创建Circle的匿名对象
		printString(new Rectangle("black", true, 5.0, 6.0));//创建Rectangle的匿名对象
	}

	public static void printString(GeometricObject go) {
    
    //动态调用toString方法
		System.out.println(go.toString());
	//运行结果:
	//GeometricObject [color=white, filled=false]  radius:3.0
    //GeometricObject [color=black, filled=true]   width:5.0   high:6.0

Six. Object conversion and instanceof

1. The reference of an object can be type converted into a reference of another object, which is called object conversion

Object o=new Student();//向下转换

//但是  Student s=o;  错误,需要显式转换

Student s=(Student)o;//向上转换,显式

When trying to explicitly convert, make sure that an object is an instance of another object, using the instancesOf keyword to achieve

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		GeometricObject[] go = {
    
     new Circle(5.0), new Rectangle("black", true, 5.0, 6.0),
				new GeometricObject("blue", true) };//创建一个GeometricObject类型的数组
		for (GeometricObject i : go) {
    
    //遍历数组中元素
			if (i instanceof Circle) {
    
    //i是否是Circle的实例
				System.out.println(((Circle) i).getArea());//因为GeometricObject 类中没有getArea方法,所以要显式转换
			} else if (i instanceof Rectangle) {
    
    //i是否是Rectangle的实例
				System.out.println(((Rectangle) i).getPrimeter());//因为GeometricObject 类中没有getPrimeter方法,所以要显式转换
			} else {
    
    //i是否是GeometricObject的实例
				System.out.println(i.toString());
			}
		}
	}
	//运行结果:
	//78.5
    //22.0
   //GeometricObject [color=blue, filled=true]

Why is it not defined as Circle type or Rectangle type from the beginning?
In order to be able to general design, the variable is defined as a parent class, so that it can receive any sub-type value

2. Object member access operator (.) takes precedence over type conversion. So you must first convert to call the method at
Rectangle Example: ((Rectangle) i).getPrimeter()

3. Note that
converting the basic type will return a new value, but converting the object does not create a new object

Object o=new Circle();
Circle c=(Circle)o;
//o和c指向同一个对象

Seven. The equals() method in the Object class

1. In the subclass, use the signature equals(SomeClassName obj) (for example: equals(Circle c) to override the equals method is wrong, you should use equals(Object obj))

	@Override
	public boolean equals(Object obj) {
    
    
		if(obj instanceof Circle) {
    
    //判断Circle是否是obj的实例
			return this.radius==((Circle)obj).getRadius();//比较两个的半径是否相等
		}
		else
			return this==obj;
	}

8. ArrayList class

1. Arraylist can be used to store a list of objects

2. Can store an unlimited number of objects

3. ArrayList is a generic class with a generic type E

4. Grammar

ArrayList<E> list=new ArrayList<E>();
                              //jdk1.7之后可以去掉这个E

5. Method

The ArrayList class contains methods such as add, clear, whether to include, find, delete, modify, etc.,
which will be mentioned below

6. The difference between array and ArrayList

Array ArrayList
definition int[] array=new array[5] ArrayList<> list=new ArrayList<>()
Quote array[index] list.get(index)
Update element array[index]=b list.set(index,b)
Return size a.length list.size()
Add new element list.add()
Insert new element list.add(index,b)
Delete an element list.remove(index)或list.remove(b)
Delete all list.clear()
Sort java.util.Arrays.sort(array) java.util.Collections.sort(list)

ArrayList is stored in objects, so use the basic type of packaging type

ArrayList<int> list=new ArrayList<>();//错误
ArrayList<Integer> list=new ArrayList<>();//正确

note

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		ArrayList<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(2);
		list.remove(1);
		System.out.println(list);//[1]删掉的是下标所对应的元素
		//如果就想删掉1 用用list.remove((Integer)1);
	}

7. Conversion between array and array list

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		String[] str= {
    
    "hello","java","fun"};
		ArrayList<String> list = new ArrayList<>(Arrays.asList(str));//将数组转为数组列表
		System.out.println(list);//[hello, java, fun]
		
		String[] str2=new String[list.size()];
		list.toArray(str2);//将数组列表转为数组
		for(String i:str2) {
    
    
			System.out.print(i+" ");//hello java fun
		}
	}

8. Find the largest and smallest in the list and shuffle the list

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		ArrayList<Integer> list = new ArrayList<>();
		for(int i=0;i<10;i++) {
    
    
			list.add(i);
		}
		System.out.println(java.util.Collections.max(list));//获取最大值 9
		System.out.println(java.util.Collections.min(list));//获取最小值 0
		
		java.util.Collections.shuffle(list);//打乱数组列表
		System.out.println(list);//[5, 7, 4, 3, 8, 9, 1, 2, 0, 6]
		
	}

Nine. Protected data and methods

1. The protected members of a class can be accessed from subclasses

2. Allow subclasses to access the data fields and methods of the parent class, but not allow non-subclass access, use the protected keyword

3. Increasing visibility:

Private (private), default (default), protected (protected), global (public)

4. Protected allows access to classes in the package and subclasses outside the package

5. The subclass can override the protected method in the parent class, but it can't weaken the accessibility of the method and can only increase it.

10. Prevent expansion and rewriting

1. A class and method modified by final cannot be extended

2. Only final can be used on local variables of methods

Eleven. Summary

Through the study of this chapter, I know the relationship between the parent class and the child class, and learn to use super to call the construction method and method of the parent class. I must remember to put it in the first sentence and learn the meaning of polymorphism (variables of the parent class can be Pointing to subclass objects), know the difference between overriding and overloading, know the reason for dynamic loading, understand the usage of up explicit conversion, down conversion and instanceof, learned the convenience of ArrayList array list, protected modifier The usage and the use of final keywords to modify classes and methods to prevent expansion.

Come on! Chapter 12 To Be More...

Guess you like

Origin blog.csdn.net/weixin_42563224/article/details/104348434