Let's give an example and then get the answer to this question:
In the market there are inkjet printers and needle printers in both forms of printer, we need to program to achieve their boot, shutdown and printing.
Building the parent class printer
Class Printer
{
void Open () {
System.out.println ("OPEN");
}
void Close () {
System.out.println ("CLOSE");
}
void print () { ///Because the two printers are printed differently, it is not possible to write a specific print in the parent class, so it is empty.
}
}
Building Subclass Hpprinter
The printer is an inkjet printer
Class Hpprinter extends Printer
{
void print () {
System.out.println ("Inkjet printing");
}
}
Building Subclass Canonprinter
This printer is a PIN printer
Class Canonprinter extends Printer
{
void print () {
SYSTEM.OUT.PRINTLN ("pin-print");
}
}
Building the main function Test implementation function
Class Test
{
public static void Main (String args[]) {
Printer HP = new Hpprinter ();
Hp.open ();
Hp.print ();
Hp.close ();
Printer Canon = new Canonprinter ();
Canon.open ();
Canon.print ();
Canon.close ();
}
}
The compilation run found no errors.
However, the computer said there is no error, there is no mistake it? Not Imagine if, if the person writing the subroutine is careless, forget the Void print () {} of the replication parent class; What's going to happen?
Of course, there is no error at compile time, however, the printer does not have the most important function, and, in this case the computer will not tell you, where there is a problem. Although this is a very low probability example, but we do not dwell on this, and look at the Yinshechudong:
Now that the problem has arisen, there is a solution, at this point, we suddenly think of the dear abstract function, it is not the right to do this?
Redefine parent class Printer
abstract class Printer
{
void Open () {
System.out.println ("OPEN");
}
void Close () {
System.out.println ("CLOSE");
}
abstract void print () {
}
}
Now when we forget the carbon print () {}; , the system is not compiled to the past, re-implementation of human-machine integration. At the same time, the following sentence to note is:
If a piece of code is semantically wrong, it should also be syntactically incorrect, such as our previous print () {}; , it is actually empty, it is in the semantics of the wrong, so there is a grammatical error, but the compiler did not recognize it. Finally, we solved the problem by using the abstract function syntax.
"Java4android" Video Learning notes-why use abstract classes?