Java learning from scratch 18 (abstract classes and interfaces), java from scratch

Source: Internet
Author: User

Java learning from scratch 18 (abstract classes and interfaces), java from scratch
1. What are abstract classes and interfaces?

Abstract classes, interfaces, and classes are a hierarchical concept and an extremely important concept in java.

An abstract class is a public template abstracted from multiple classes and provides all the functions of sub-classes.

Interfaces are abstracted from multiple classes and reflect the principles of standardization and implementation separation. At the same time, they effectively solve the defects of java single-inheritance.

Ii. Differences between abstract classes 2.1 and normal classes
  • Abstract keywords exist before the class of an abstract class.
/** Abstract class */public abstract class Person1 {}/ ** common class */public class Person {}
  • Abstract classes can have abstract methods and common methods, while normal classes can only have common methods.
  • Common classes can be instantiated using new, while abstract classes cannot be instantiated.
2.2 differences between abstract methods and common methods
  • Abstract keywords exist before abstract methods, while normal methods do not.
  • Abstract methods do not have a method body, while common methods do.
/** Abstract Method */public abstract void show (); // No method body/** common method */public void show () {System. out. println ("this is a common method");}/** there cannot be abstract methods in a common class */
2.3 complete comparison of two categories
Package com. pb. demo3;/** common class */public class Person {private String name; // name private int age; // age/** common method */public void show () {System. out. println ("this is a normal method");}/** there cannot be an abstract method in a common class * // setter/getter method public String getName () {return name ;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}
Package com. pb. demo3;/** abstract class */public abstract class Person1 {private String name; // name private int age; // age/** abstract Method */public abstract void show (); // there is no method body. // The abstract class can have the common public void printSelf () {System. out. println ("this is a common method in an abstract class");} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}
2.4 If the abstract class is inherited
  • If the subclass is not an abstract class, you must override all abstract methods of the parent class abstract class. (Rewrite or do not write a normal method)
Package com. pb. demo3;/** Student class inherited Person1 abstract class */public class Student extends Person1 {// when inheriting, the abstract method of the parent class @ Override public void show () is forcibly required () {System. out. println ("override the abstract method of the parent class ");}}
2.5. Notes
  • Abstract cannot be used with the final keyword
  • The private keyword cannot modify the abstract method.
  • Abstract: The abstract method modified does not have a method body.
2.6. Image Comparison

Iii. Interface 3.1, Interface Definition

The interface is defined using the interface keyword.

Simply put, an interface is a type that cannot be instantiated and can only have abstract methods.

Public interface name {abstract method}
public interface Person {}
Package com. pb. demo4; public interface Person {/** defines two Abstract METHODS */public void run (); public void say ();}
. Why does the abstract keyword not need to be used for abstract methods in the interface?

Because the interface can only have abstract methods, you do not need to use abstract keywords to modify them. Of course, you can add them, but they are completely unnecessary.

3.3 abstract methods of interfaces

Abstract methods of interfaces can only be modified by public.

4. Use abstract classes and interfaces 4.1 and abstract classes to implement inheritance
/** Abstract class */public abstract class Person {/** common method */public void run () {System. out. println ("common method of abstract class! ");}/** Abstract Method */public abstract void say ();}
/** Inherit the abstract class */public class Student extends Person {@ Override public void say () {System. out. println ("implements the abstract method of the parent class! Let's talk about ");}}
Public class Test {public static void main (String [] args) {// declare the subclass object Student stu = new Student (); // call the stu method to override the subclass. say (); // call the common method stu of the parent class. run ();}}

Result:

Implements the abstract method of the parent class! Let's talk about the common methods of abstract classes! Take a walk
4.2 Use of interfaces

Use implements to implement interfaces to solve the single inheritance relationship in java. The interfaces can be multiple

Package com. pb. demo4; public interface Person {/** defines two Abstract METHODS */public void run (); public void say ();}
Package com. pb. demo4;/** implement the interface Person */public class PersonImp implements Person {/** all the Abstract methods of the interface must be overwritten */@ Override public void run () {System. out. println ("abstract methods for implementing interfaces");} @ Override public void say () {System. out. println ("abstract methods for implementing interfaces ");}}
Package com. pb. demo4; public class Test {public static void main (String [] args) {// declare the object PersonImp p = new PersonImp (); // call the implemented Method p. run (); p. say ();}}

Result:

An abstract method is used to implement an interface.
4.3 comparison implementation

V. Simple differences between abstract classes and interfaces 5.1. Differences
  • Use of abstract classesAbstract declaration,Interface UsageInterfaceStatement
  • Abstract classes can haveAbstract methods can also have common methods,InterfaceOnly abstract methods are allowed.
  • Different implementation methods:Use of abstract classesInherit extends to implement, Interface UsageImplements to implement
5.2 similarities
  • Abstract classes and interfacesCannot be instantiated
5.3 graphic comparison

5.4 use rules
  • Abstract classes and interfacesCannot be instantiated
  • Abstract classes and interfacesWhen it is inherited and implemented, its subclass must implement the abstract method.
  • The abstract method access modifier in the abstract class cannot be private, and the abstract method access modifier in the interface must be public

6. Simple implementation of abstract classes
Package com. pb. demo5;/** Bird abstract class */public abstract class Bird {/** normal method of flying */public void fly () {System. out. println ("ejection fly! ");}/** Attack abstraction method */public abstract void attack ();}
Package com. pb. demo5;/** rocket Bird */public class RocketBird extends Bird {/** rewrite attack method */@ Override public void attack () {System. out. println ("Rocket and bird attack method: accelerated collision! ");}}
Package com. pb. demo5;/** Split Bird */public class SplittBird extends Bird {/** rewrite attack method */@ Override public void attack () {System. out. println ("Split Bird attack method: Split attack! ");}}
Package com. pb. demo5; public class Test {public static void main (String [] args) {/** polymorphism application * // create a bird object, instantiate it as the Split Bird object Bird splitbird = new SplittBird (); // create a Bird object and instantiate it as the rocket Bird object Bird rocketbird = new RocketBird (); // call the methods of normal flight of birds respectively // call the method called after the subclass rewriting // call the attacked method splitbird after the subclass rewriting respectively. fly (); splitbird. attack (); rocketbird. fly (); rocketbird. attack ();}}

Result:

Ejection flight! Split Bird attack method: Split attack! Ejection flight! Rocket and bird attack methods: accelerated collision!

As shown in the preceding example:Same Class MethodSuch as the Flying MethodYou can use a common method in the abstract class of the parent class to implement code reuse. Different Parts use abstract methods and subclasses to implement their own methods. Simply put: abstract classes are implemented by extracting public parts in abstraction.

For example, there are no identical methods, but all of them have this method. How can this problem be achieved? At this time, the interface is required.

VII. simple interface implementation

Let's take the preceding example as an example. For example, if there is a calling method, what about the sounds of every bird? Some will be called, some will not,

Package com. pb. demo5;/** called interface */public interface Shout {/** called Method */public void shout ();} package com. pb. demo5; public class AoShoutImpl implements Shout {@ Override public void shout () {System. out. println ("too many! ") ;}} Package com. pb. demo5; public class ZhaShoutImpl implements Shout {@ Override public void shout () {System. out. println ("! ") ;}} Package com. pb. demo5; public class NoCanShoutImpl implements Shout {@ Override public void shout () {System. out. println (" No! ");}}
Package com. pb. demo5;/** Bird abstract class */public abstract class Bird {Shout shout;/** constructor */public Bird (Shout shout) {super (); this. shout = shout;}/** common method */public void shout () {// call the shout method. shout ();}/** normal method of flying */public void fly () {System. out. println ("ejection fly! ");}/** Abstract attack method */public abstract void attack ();}
Package com. pb. demo5;/** bomb Bird */public class Bombbird extends Bird {public Bombbird (Shout shout) {super (shout) ;}@ Override public void attack () {System. out. println ("bomb bird attack mode: Bomb Attack") ;}@ Override public void shout () {System. out. println ("bomb bird: scream! ") ;}} Package com. pb. demo5;/** fat Bird */public class Fatbird extends Bird {public Fatbird (Shout shout) {super (shout) ;}@ Override public void attack () {System. out. println ("fat bird attack method: Egg attack") ;}@ Override public void shout () {System. out. println ("Fat Bird: No! ") ;}} Package com. pb. demo5;/** red Bird */public class Redbird extends Bird {public Redbird (Shout shout) {super (shout) ;}@ Override public void attack () {System. out. println ("red bird attack method: normal attack") ;}@ Override public void shout () {System. out. println ("red bird: scream! ") ;}} Package com. pb. demo5; import com. pb. demo5.Bird;/** rocket Bird */public class RocketBird extends Bird {public RocketBird (Shout shout) {super (shout );} /** rewrite attack method */@ Override public void attack () {System. out. println ("Rocket and bird attack method: accelerated collision! ");}/** Rewrite the Method */@ Override public void shout () {System. out. println (" Rocket bird: Rocket bird! ") ;}} Package com. pb. demo5;/** Split Bird */public class SplittBird extends Bird {public SplittBird (Shout shout) {super (shout );} /** rewrite attack method */@ Override public void attack () {System. out. println ("Split Bird attack method: Split attack! ");}/** Rewrite the method called */@ Override public void shout () {System. out. println (" Split Bird: called zookeeper! ");}}
Package com. pb. demo5; import com. pb. demo5.Bird; public class Test {public static void main (String [] args) {/** create interface object */Shout aoshout = new AoShoutImpl (); shout zhashout = new ZhaShoutImpl (); Shout noshout = new NoCanShoutImpl ();/** polymorphism application * // create a bird object, instantiated as the Split Bird object Bird splitbird = new SplittBird (aoshout); Bird rocketbird = new RocketBird (aoshout); Bird bomb = new Bombbird (zhashout ); bird redbird = new Redbird (zhashout); Bird fatbird = new Fatbird (noshout); splitbird. fly (); splitbird. attack (); splitbird. shout (); rocketbird. fly (); rocketbird. shout (); rocketbird. attack (); bomb. fly (); bomb. shout (); bomb. attack (); redbird. fly (); redbird. shout (); redbird. attack (); fatbird. fly (); fatbird. shout (); fatbird. attack ();}}

Result:

Ejection flight! Split Bird attack method: Split attack! Split the bird: the hacker is called! Ejection flight! Rocket bird! Rocket and bird attack methods: accelerated collision! Ejection flight! Bomb bird: scream! Bomb bird attack method: Bomb Attack ejection fly! Red bird: scream! Red Bird attack mode: normal attack ejection! Fat Bird: No! Fat bird attack method: Egg attack

It can be seen from the above: abstract classes facilitate code reuse, and interfaces facilitate code Maintenance

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.