Java core technology: an in-depth understanding of abstract classes and interfaces

Source: Internet
Author: User
Tags getcolor

Java core technology: an in-depth understanding of abstract classes and interfaces
1. General description

Abstract class
Template Method Mode
Interface

2 abstract class

Abstract classes are classes that cannot be instantiated. They are generally designed to inherit from quilt classes to implement abstract methods of parent classes.
The biggest difference from a common class is that it cannot be instantiated. You can declare an abstract method to implement a subclass.
Member variables and common methods can be defined.

package tony.javacore.oop.abstractclass;import static tony.javacore.util.io.PrintUtils.println;/** * 

Abstract parent Shape

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name Shape. java * @ see * @ version August 30, 2015 10:20:19 * @ since JDK8.0u45 */public abstract class Shape {private String color; // graphic color/* get set */public String getColor () {return color;} public void setColor (String color) {this. color = color;}/* default Constructor */public Shape () {println (Execute Shape Constructor Method);}/* overload Constructor */public Shape (String color) {println (Execute Shape Constructor Method: Color is + color); this. color = color;}/*** method for defining the abstract calculation perimeter * @ return * @ version August 30, 2015 10:21:10 * @ since */public abstract double calPerimeter (); /*** return the abstract method of the image shape * @ return * @ version August 30, 2015 10:22:53 * @ since */public abstract String getType ();}

When the subclass inherits the abstract class, the abstract method of the abstract parent class must be implemented.

package tony.javacore.oop.abstractclass;/** *  * 

Define subclass circle

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name Circle. java * @ see * @ version August 30, 2015 10:25:35 * @ since JDK8.0u45 */public class Circle extends Shape {private double radius; // subclass special attribute radius/* get set */public double getRadius () {return radius;} public void setRadius (double radius) {this. radius = radius;}/*** subclass Circle constructor * @ param color * @ param radius */public Circle (String color, double radius) {super (color); this. radius = radius;} @ Override public double calPerimeter () {return 2 * Math. PI * radius; // the circumference of the circle is 2r} @ Override public String getType () {return getColor () + circle;} @ Override public String toString () {return Circle [radius = + radius +];}

Subclass can have its own unique attributes and Methods

package tony.javacore.oop.abstractclass;import static tony.javacore.util.io.PrintUtils.println;/** * 

Triangle

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name Triangle. java * @ see * @ version August 30, 2015 10:28:35 * @ since JDK8.0u45 */public class Triangle extends Shape {/* defines three sides of a Triangle */private double one; private double two; private double three; public Triangle (String color, double one, double two, double three) {super (color); setSides (one, two, three );} /*** create three sides of a triangle object * @ param one * @ param two * @ param three * @ version 10:33:22 on January 1, August 30, 2015 * @ since */public void setSides (double one, double two, double three) {if (one> = two + three | two> one + three | three> one + two) {println (the sum of the two sides must be longer than the third side); return;} this. one = one; this. two = two; this. three = three ;}@ Override public double calPerimeter () {return one + two + three ;}@ Override public String getType () {return super. getColor () + Triangle;} @ Override public String toString () {return Triangle [one = + one +, two = + two +, three = + three +];}

When the parent class reference (Shape shape) points to the subclass object (Circle), polymorphism occurs.
In this case, if you use the reference of the parent class to call the methods defined in the parent class, the runtime actually calls the subclass method, and the method of the parent class with the same name is overwritten.

package tony.javacore.oop.abstractclass;import static tony.javacore.util.io.PrintUtils.println;/** * 

Abstract class test cases

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name ShapeHandler. java * @ see * @ version August 30, 2015 10:35:11 * @ since JDK8.0u45 */public class ShapeHandler {public static void main (String [] args) {Shape circle = new Circle (red, 2.2); Shape triangle = new Triangle (Green, 3.0, 4.0, 5.0); println (circle perimeter: + circle. calPerimeter (); println (triangle perimeter: + triangle. calPerimeter (); println (circle. getType ());}}3. template method mode

The template method mode is the behavior mode of the class.
Prepare an abstract class, implement part of the logic in the form of a specific method and a specific constructor, and then declare some abstract methods to force the subclass to implement the remaining logic. Different sub-classes can implement these abstract methods in different ways to implement the residual logic differently.

Define the abstract parent class for processing flight message templates
Template Method: Convert the message after receiving the message, and then perform business logic processing for the message.
Abstract method: mainly refers to the method declaration for message conversion and business logic.

package tony.javacore.oop.abstractclass;import tony.javacore.oop.abstractclass.bean.MessageBean;/** * 

Abstract parent class of Message Processing

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name MsgHandlerAbs. java * @ see * @ version August 30, 2015 11:38:49 * @ since JDK8.0u45 */public abstract class MsgHandlerAbs {/*** Message Processing Template Method * @ param object * @ version August 30, 2015 11:44:05 * @ since */public final void handleMessage (Object object) {try {MessageBean msgBean = new MessageBean (); if (msgBean instanceof MessageBean) {msgBean = (MessageBean) object;} else {msgBean. setMessage (object);} Object newObj = parseMsg (msgBean); handleBussiness (newObj);} catch (Exception e) {}/*** re-process the parsed message and convert it into the entity required for subsequent processing by the Program (including the original entity) * @ param messageBean * @ return * @ version August 30, 2015 11:44:14 * @ since */public abstract Object parseMsg (MessageBean messageBean ); /*** perform logical processing on the re-processed object * @ param Object * @ version 11:45:07 on January 1, August 30, 2015 * @ since */public abstract void handleBussiness (object Object );}

Message entity, including the object corresponding to the Message Type and type

package tony.javacore.oop.abstractclass.bean;/** * 

Message entity, including the object corresponding to the Message Type and type

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass. bean * @ file_name MessageBean. java * @ see * @ version August 30, 2015 11:53:27 * @ since JDK8.0u45 */public class MessageBean {private String msgType; // Message Type private String uniqueKey; // private Object message, the unique key value of the message; // message Object public String getMsgType () {return msgType;} public void setMsgType (String msgType) {this. msgType = msgType;} public String getUniqueKey () {return uniqueKey;} public void setUniqueKey (String uniqueKey) {this. uniqueKey = uniqueKey;} public Object getMessage () {return message;} public void setMessage (Object message) {this. message = message ;}}

The flight message processing on the route point inherits from the abstract parent class MsgHandlerAbs to Implement Message conversion and message service logic processing on the corresponding route point.

package tony.javacore.oop.abstractclass.message;import tony.javacore.oop.abstractclass.MsgHandlerAbs;import tony.javacore.oop.abstractclass.bean.MessageBean;/** * 

Flight Message Processing on Route points

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass * @ file_name PointFlightInfoMsgHandler. java * @ see * @ version August 30, 2015 11:47:10 * @ since JDK8.0u45 */public class PointFlightInfoMsgHandler extends MsgHandlerAbs {@ Override public Object parseMsg (MessageBean messageBean) {// convert the sent message to Bean return null for the corresponding route point flight message;} @ Override public void handleBussiness (Object object Object) {// process the flight message business logic on the route point }}

Flight message processing at an airport point inherits from the abstract parent class MsgHandlerAbs to Implement Message conversion and message service logic processing at the corresponding airport point.

package tony.javacore.oop.abstractclass.message;import tony.javacore.oop.abstractclass.MsgHandlerAbs;import tony.javacore.oop.abstractclass.bean.MessageBean;/** * 

Airport Flight Message Processing

* @ Author tony 18616939520@163.com * @ project_name JavaCore * @ package_name tony. javacore. oop. abstractclass. message * @ file_name AirportInfoMsgHandler. java * @ see * @ version August 31, 2015 12:00:31 * @ since JDK8.0u45 */public class AirportInfoMsgHandler extends MsgHandlerAbs {@ Override public Object parseMsg (MessageBean messageBean) {// convert the passed message entity to the airport point message Bean return null;} @ Override public void handleBussiness (Object object Object) {// business logic for handling flight messages at the airport }}4 Interface

Interfaces reflect the idea of separation between specifications and implementations.
The biggest difference from an abstract class is that a common method cannot be defined, which means that a method can only be an abstract method (only a method declaration is required for the Implementation class of the implemented interface to implement the declared method ), the interface can inherit multiple interfaces.
The member variables are modified using static final by default, that is, static constants.
After JDK8.0, you can define the default method in the interface. The default method can be implemented.
After JDK8.0, class methods can be defined in the interface (that is, the static modification method)

In Java Web development, interfaces and implementations are usually used to achieve hierarchical business development.
For example, in the DAO layer, declare common data access methods, and then let the subclass implement
The Spring-encapsulated SqlSessionTemplate is used for implementation. To implement other implementation classes (such as Spring JDBC), you only need to inherit from DaoManager.

Define common data access interfaces

package tony.shopcenter.common.dao;import java.sql.Connection;import java.sql.SQLException;import java.util.List;import java.util.Map;import tony.shopcenter.common.page.PagerModel;/** * 

Unified database access interface

* @ Author tony 18616939520@163.com * @ project_name ShopCenter * @ package_name tony. shopcenter. dao * @ file_name DaoManager. java * @ see tony. shopcenter. common. page. pagerModel * @ version August 27, 2015 11:14:47 * @ since JDK8.0u45 */public interface DaoManager > ********** * *************/Public int insert (String statement ); public int insert (String statement, Object... parametes ); /************************* delete a record ************ * ************/public int delete (String statement ); public int delete (String statement, Object... parameters ); ************ * ***********/public int udpate (String statement ); public int update (String statement, Object... parameters ); ************ * ************/public T selectOne (String statement); public T selectOne (String statement, Class RequiredType, Object... parameters); public Map SelectMap (String statement, String mapKey); public Map SelectMap (String statement, String mapKey, Object... parameters); public List SelectList (String statement); public List SelectList (String statement, Object... parameters ); /************************* obtain data connection information ********** * **************/public Connection getConnection () throws SQLException ;}

Unique Batch Data Processing of MyBatis

package tony.shopcenter.common.dao;import java.util.List;import tony.shopcenter.common.page.PagerModel;/** * 

MyBatisBaseDao data access interface

* @ Author tony 18616939520@163.com * @ project_name ShopCenter * @ package_name tony. shopcenter. common. dao * @ file_name MyBatisBaseDao. java * @ see * @ version August 27, 2015 12:57:36 * @ since JDK8.0u45 * @ param */Public interface MyBatisBaseDao Extends DaoManager {/*** Batch add, modify, and delete * @ param statement * @ param list * @ return */public int batchUpdate (String statement, List List );}

Use Spring to encapsulate the SqlSessionTemplate of MyBatis to complete database data operations

package tony.shopcenter.common.dao.impl;import java.sql.Connection;import java.sql.SQLException;import java.util.List;import java.util.Map;import org.mybatis.spring.SqlSessionTemplate;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Repository;import tony.shopcenter.common.dao.MyBatisBaseDao;import tony.shopcenter.common.page.PagerModel;/** * 

* MyBatis Data Access implementation *

* @ Author tony 18616939520@163.com * @ project_name ShopCenter * @ package_name tony. shopcenter. common. dao. impl * @ file_name MyBatisBaseDaoImpl. java * @ see * @ version August 27, 2015 4:08:16 * @ since JDK8.0u45 */@ Repository public class MyBatisBaseDaoImpl Implements MyBatisBaseDao {// Use Spring to encapsulate SqlSessionTemplate of MyBatis to perform database data operations @ Value (sqlSessionTemplate) private SqlSessionTemplate sqlSessionTemplate; @ Override public int insert (String statement) {return sqlSessionTemplate. insert (statement) ;}@ Override public int insert (String statement, Object... parameters) {return sqlSessionTemplate. insert (statement, parameters) ;}@ Override public int delete (String statement) {return sqlSessionTemplate. delete (statement) ;}@ Override public int delete (String statement, Object... parameters) {return sqlSessionTemplate. delete (statement, parameters) ;}@ Override public int udpate (String statement) {return sqlSessionTemplate. update (statement) ;}@ Override public int update (String statement, Object... parameters) {return sqlSessionTemplate. update (statement, parameters) ;}@ Override public T selectOne (String statement) {return sqlSessionTemplate. selectOne (statement) ;}@ Override public T selectOne (String statement, Class RequiredType, Object... parameters) {return sqlSessionTemplate. selectOne (statement, parameters) ;}@ Override public Map SelectMap (String statement, String mapKey) {return sqlSessionTemplate. selectMap (statement, mapKey) ;}@ Override public Map SelectMap (String statement, String mapKey, Object... parameters) {return sqlSessionTemplate. selectMap (statement, parameters, mapKey);} @ Override public List SelectList (String statement) {return sqlSessionTemplate. selectList (statement) ;}@ Override public List SelectList (String statement, Object... parameters) {return sqlSessionTemplate. selectList (statement, parameters) ;}@ Override public int batchUpdate (String statement, List List) {return this. update (statement, list) ;}@ Override public Connection getConnection () throws SQLException {return sqlSessionTemplate. getConnection ();}}

For the use cases of interfaces and abstract classes, you can read the JDK's Collection framework API, Collection interface, and common implementation classes such as ArrayList, collections list, HashSet, and TreeSet.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.