How does the parent class call the method of the subclass in Java

  • 2021-07-18 08:02:35
  • OfStack

Can the parent class call the methods of the subclass?

A: Yes.

How?

Pass the subclass into the parameterized construction of the parent class, and then call. Use reflection to call. You use reflection. Who else can't call? ! The parent class calls the static method of the subclass.

Case presentation:


package com.ywq;

public class Test2{	
	public static void main(String[] args)
	{
		Son son = new Son();
		Father father=new Father(son);
		father.fun1();
		father.fun4();
	}	
}
class Father{
	public Son son;
	public Father(Son son){		
		this.son=son;
	}	
	public Father() {
		
	}
 
	public void fun4(){
		// Method 3 Call subclass methods using reflection 
		try {
			Class cls=Class.forName("com.ywq.Son");
			Son son=(Son) cls.newInstance();
			son.fun2();
		} catch (Exception e) {
		
			e.printStackTrace();
		}
	}
	public void fun1(){
		// Method 1 Pass the subclass into the parameterized constructor of the parent class, and then call. 
		System.out.println(" I am the method of the parent class ");
		son.fun2();
		
		// Method 2 The parent class calls the static method of the subclass. 
		Son.fun3();
	}		
}
 
class Son extends Father{
	
	public static void fun3(){
		System.out.println(" I am a static method of a subclass ");
	}
	public void fun2(){
		System.out.println(" I am a subclass method ");
		
	}
	
}

All three are methods in which the parent class directly calls the subclass,

Is it easy to use? Easy to use!

Have you solved the problem? It's solved!

Is it allowed in the project? Not allowed!

I didn't understand why I used the parent class to call the method of the subclass. If 1 must call a subclass, why inherit it? I don't understand. In fact, this problem can be understood from another angle. The parent class builds a framework, and the subclass rewrites the method of the parent class and then calls the method inherited from the parent class, resulting in different results (and this is the template method pattern). Can this also be understood as the parent class calling the subclass's method? You modify the subclass, which affects the behavior of the parent class. The curve salvation method realizes the scene that the parent class depends on the subclass, and the template method pattern is this effect.


Related articles: