Java parent class calls methods overridden by child classes

1. If the parent class constructor calls the method overridden by the subclass, and the subclass object is created through the subclass constructor, and the parent class constructor (whether explicit or implicit) is called, it will cause the parent class to construct What is actually called is the method overridden by the subclass (you need to understand the initialization mechanism in java inheritance).

public abstract class Father {  
    public Father() {  
        display();  
    }  
  
    public void display() {  
        System.out.println("Father's display");  
    }     
}

 

public class Son extends Father {  
  
    public Sound() {  
    }  
  
    public void display() {  
        System.out.println("Son's display");  
    }  
      
    public static void main(String[] args) {  
        new Son();  
    }  
  
}

The output is:

Son's display

 

This mechanism has advantages, but sometimes problems.


Advantages: By inheriting the same parent class, when the subclass is initialized, the parent class will call different overriding methods of different subclasses, thus achieving polymorphism.

To give an example in Spring:
Spring can execute SQL statements by injecting a JdbcTemplate that has been initialized with a DataSource for each DAO. However, each DAO implements this injection through coding, resulting in a lot of code redundancy, so Spring provides a JdbcDaoSupport class. DAO only needs to inherit this class, and it will automatically inject the initialized JdbcTemplate, so how to do it? ?

View the source code:
JdbcDaoSupport inherits DaoSupport:

public abstract class JdbcDaoSupport extends DaoSupport

DaoSupport implements the InitializingBean interface, which has only one void afterPropertiesSet() throws Exception;
method. Spring will check whether the bean implements the InitializingBean interface after initializing the bean's properties. If it inherits, it will automatically call the afterPropertiesSet method.

 

Then look at how the afterPropertiesSet in DaoSupport is implemented:

public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {  
	// Let abstract subclasses check their configuration.  
	checkDaoConfig();  

	// Let concrete implementations initialize themselves.  
	try {  
		initDao ();  
	}  
	catch (Exception ex) {  
		throw new BeanInitializationException("Initialization of DAO failed", ex);  
	}  
}

He calls the checkDaoConfig method here, which is an abstract method, and will call the method overridden by the subclass at runtime.

See how JdbcDaoSupport overrides checkDaoConfig():

@Override  
protected void checkDaoConfig() {  
	if (this.jdbcTemplate == null) {  
		throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");  
	}  
}  

JdbcDaoSupport will check whether jdbcTemplate is injected, if not, an exception will be thrown! This completes the process of injecting detection and implementing specific detection through subclasses! This is why an exception is thrown when your DAO inherits JdbcDaoSupport, but does not configure the DataSource property when configuring the DAO in XML.

So when is JdbcTemplate injected? Observe the JdbcDaoSupport source code and find the setDataSource() method. When the framework initializes the DAO according to the XML configuration, it will call the attribute's set method injection. If the DAO does not have the set method, the parent class will be called. That is, the setDataSource method of JdbcDaoSupport is called, and the jdbcTemplate required by DAO to execute SQL statements is created.

/**
 * Set the JDBC DataSource to be used by this DAO.
 */  
public final void setDataSource(DataSource dataSource) {  
	if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {  
		this.jdbcTemplate = createJdbcTemplate(dataSource);  
		initTemplateConfig();  
	}  
}

 

Disadvantage: If the method overridden by the subclass is called in the constructor of the parent class, it will cause the method overridden by the subclass to be executed before all the code in the constructor of the subclass, so that the method overridden by the subclass cannot access the instance of the subclass The value of the variable, because these variables have not been initialized at this time.

 

Transfer: http://blog.csdn.net/zhuoaiyiran/article/details/19489745

 

Guess you like

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