Original article, if reproduced, please indicate the source: http://blog.csdn.net/yihui823/article/details/6932952
After separating a piece of code and business logic, let's take a look.
Base class:
Package testjava;/*** base class */public class basebook {private int type =-1; Public basebook (INT type) {This. type = type;}/*** print page */Public void printpage () {If (type = 1) {system. out. println ("Print with the green color. ");} else if (type = 2) {system. out. println ("Print with the blue color. ");} else {system. out. println ("Print with the white color. ");}}}
Subclass 1:
Package testjava;/*** Green Book */public class Greenbook extends basebook {public Greenbook (INT type) {super (type );} /*** get color * @ return color */Public String getcolor () {return "green ";}}
Subclass 2:
Package testjava;/*** Blue Book */public class Bluebook extends basebook {public Bluebook (INT type) {super (type );} /*** get color * @ return color */Public String getcolor () {return "blue ";}}
Called class:
Package testjava;/*** execution class */public class testjava {/*** @ Param ARGs the command line arguments */public static void main (string [] ARGs) {Bluebook BB = new Bluebook (2); bb. printpage (); Greenbook GB = new Greenbook (1); GB. printpage ();}}
Of course, the running result is correct. However, the behavior of subclass is defined in the parent class. That is to say, the "Books" of the base class are judged by the color of each book.
If (type = 1 ){
System. Out. println ("Print with the green color .");
} Else if (type = 2 ){
System. Out. println ("Print with the blue color .");
} Else {
System. Out. println ("Print with the white color .");
}
This structure has poor scalability, maintenance, and reading skills.
Ask the client. The client said that I cannot know which subclass the parent class is. However, this service can be extracted, so it is written as this.
Actually, it can be written like this.
Base class:
Package testjava. right;/*** base class */public abstract class basebook {public abstract string getcolor ();/*** print page */Public void printpage () {system. out. println ("Print with the" + getcolor () + "color. ");}}
Subclass 1:
Package testjava. right;/*** Blue Book */public class Bluebook extends basebook {/*** get color * @ return color */Public String getcolor () {return "blue ";}}
Subclass 2:
Package testjava. right;/*** Green Book */public class Greenbook extends basebook {/*** get color * @ return color */Public String getcolor () {return "green ";}}
Execution class:
Package testjava. right;/*** execution class */public class testjava {/*** @ Param ARGs the command line arguments */public static void main (string [] ARGs) {Bluebook BB = new Bluebook (); bb. printpage (); Greenbook GB = new Greenbook (); GB. printpage ();}}
Define the behavior that belongs to the subclass as an abstract function, which is implemented by the subclass. OK