Java Object-oriented programming (eight)--abstract class, interface

Source: Internet
Author: User

1. Abstract class

1.1 Abstract class concepts

When some methods of the parent class are not deterministic, you can use the abstract keyword to decorate the method [abstract method] and use abstract to decorate the class [abstract class].

//the necessity of abstract classes [Demo124.java] Public classDemo124 { Public Static voidMain (string[] args) {//Animal an=new Animal (); Abstract class does not allow instantiationAnimal an=NewCat ();        An.cry (); an=NewDog ();    An.cry (); }}//Abstract KeywordsAbstract classanimal{String name; intAge ; //animals will be called, using the abstract abstraction method
    abstract public void Cry ();     
    //there can be an implementation method within an abstract class     Public voidsx () {System.out.println ("Implementation Method"); }}//when a subclass inherits a parent class that is abstract, it requires the programmer to implement all the abstract methods of the abstract class. classCatextendsanimal{//implements the cry of the parent class, in fact, similar to the subclass in the last section of the study overriding the parent class     Public voidcry () {System.out.println ("Cat's name."); }}classDogextendsanimal{//implements the cry of the parent class, in fact, similar to the subclass in the last section of the study overriding the parent class     Public voidcry () {System.out.println ("Bark."); }}

1.1. Abstract class -- In- depth discussion

Abstract classes are one of the more important classes in Java.

1. When you use the abstract keyword to modify a class, this class is an abstract class.

2, when using the abstract keyword to modify a method, this method is an abstract method.

3. Abstract abstractions in abstract classes are not allowed to be implemented in abstract classes, and once implemented are not abstract methods and abstract classes. Abstract abstraction methods can only be implemented in subclasses.

4, the abstract class can have the implementation method.

5, the abstract method in the programming is not a lot, but in the company's written test, but the examiner is more love to ask the knowledge points.

1.2. Abstract class -- Precautions

1. Abstract classes cannot be instantiated

2. Abstract classes do not necessarily include abstract methods. In other words, abstract classes can have no abstract abstraction method.

3. Once the class contains an abstract abstraction, the class must be declared abstract.

4, abstract methods can not have a subject.

Example of correct abstract method: abstract void ABC ();

Example of an abstract method of the wrong language: abstract void abc () {}

2. Interface

2.1. What is an interface?

Interface is to give some methods without content, encapsulated together, to a class to use, in accordance with the specific circumstances of these methods written.

The build syntax for the interface:

Interface Interface Name {    method;}

Implement interface Syntax:

class Implements interface {      method;      variable;}

An interface is a more abstract class, and a method in an abstract class can have a method body, and all methods in an interface have no method body. The interface embodies the design idea of multi-state and high-cohesion low-coupling in programming.

Case:

//implementation of the interface [Demo125.java]//computer, Camera, U-disk, mobile//USB InterfaceInterfaceusb{intA=1;//The addition of static, not to be modified with private and protected//two methods were declared     Public voidStart ();//interface starts to work     Public voidStop ();//interface stops working}//a camera class was written, and a USB interface was implemented//an important principle: When a class implements an interface, it requires that the class implement all the methods of this interfaceclassCameraImplementsusb{ Public voidstart () {System.out.println ("I'm the camera and I'm working."); }     Public voidStop () {System.out.println ("I'm the camera, stop working ..."); }}//interfaces inherit other interfacesclassbase{}Interfacett{}InterfaceSonextendstt{}//wrote a mobile phone, and implemented a USB interfaceclassPhoneImplementsusb{ Public voidstart () {System.out.println ("I'm a cell phone and I'm working."); }     Public voidStop () {System.out.println ("I'm a cell phone, stop working ..."); }}//Computerclasscomputer{//Getting started with the USB interface     Public voidUSEUSB (USB usb) {Usb.start ();    Usb.stop (); }} Public classDemo125 { Public Static voidMain (string[] args) {System.out.println (USB.A); //Create ComputerComputer computer=Newcomputer (); //Create a cameraCamera camera=NewCamera (); //Create phonePhone phone=NewPhone ();        COMPUTER.USEUSB (camera);    COMPUTER.USEUSB (phone); }}

Precautions

(1), interface cannot be instantiated

(2), all methods in the interface cannot have a subject. Error syntax example: void aaa () {}← (note cannot have curly braces)

Interfaces can be thought of as abstract classes that are more abstract.

(3), a class can implement a plurality of interfaces

(4), the interface can have variables [but variables cannot be modified with private and protected]

A, the variables in the interface are essentially static and final type, whether you add static modifiers or not

b, in Java development, we often use common variables, defined in the interface, as a global variable used

Access form: interface name. variable Name

(5), an interface cannot inherit other classes, but can inherit other interfaces

3. Implementing interface Vs Inheriting Class

Java inheritance is a single inheritance, that is, a class can have at most one parent class, this mechanism of single inheritance can guarantee the purity of the class, more concise than the multi-inheritance mechanism in C + +. However, there is no denying that the extension of the function of sub-class has certain effect. So:

1, the implementation of the interface can be seen as a complement to inheritance. (Inheritance is hierarchical and less flexible.) Modifying a class breaks the balance of inheritance, and the interface has no such trouble because it only works on classes that implement the interface)

2, the implementation of the interface can not break the inheritance relationship under the premise of a class function extension, very flexible.

//Example: Creating a subclass and inheriting a parent class and connecting multiple interfaces [Demo126.java] Public classDemo126 { Public Static voidMain (string[] args) {System.out.println ("Inherited the Monkey Parent class"); Monkey Mo=NewMonkey ();        Mo.jump (); Littlemonkey Li=NewLittlemonkey ();        Li.swimming ();    Li.fly (); }}//Interface FishInterfacefish{ Public voidswimming ();}//Interface BirdInterfacebird{ Public voidfly ();}//Establish Monkey classclassmonkey{intname; //Monkeys can jump     Public voidJump () {System.out.println ("Monkeys can jump!"); }}//established the Littlemonkey subclass and inherited the monkey parent class and connected the fish and bird interfacesclassLittlemonkeyextendsMonkeyImplementsfish,bird{ Public voidswimming () {System.out.println ("The Fish interface is connected!"); }     Public voidFly () {System.out.println ("Connected to the bird interface!"); }}

4, using the interface to achieve polymorphism

Polymorphism in Java is a difficult concept to understand, but it is also a very important concept. One of the three major features of Java (inheritance, encapsulation, polymorphism), we can literally understand: is a type of multiple states, the following by selling a car example shows what is polymorphic.

Case:

//using interfaces to achieve polymorphic Public classDemo127 { Public Static voidMain (String []args) {Carshop ashop=NewCarshop (); //sell a BMWAshop.sellcar (NewBMW ()); //sell a Chery QQAshop.sellcar (Newcheryqq ()); //Sell a SantanaAshop.sellcar (NewSantana ()); System.out.println ("Total Revenue:" +Ashop.getmoney ()); }}//Automotive InterfaceInterfacecar{//Car nameString getName (); //get the car price    intGetPrice ();}//BMWclassBMWImplementscar{ PublicString GetName () {return"BMW"; }     Public intGetPrice () {return300000; }}//Chery QQclassCheryqqImplementscar{ PublicString GetName () {return"Cheryqq"; }     Public intGetPrice () {return20000; }}//Santana CarclassSantanaImplementscar{ PublicString GetName () {return"Santana"; }     Public intGetPrice () {return80000; }}//Car Selling Shopclasscarshop{//Car Sales revenue    Private intMoney=0; //Sell a car     Public voidSellcar (car car) {System.out.println ("Model:" +car.getname () + "unit Price:" +Car.getprice ()); //increase the selling price of the car revenuemoney+=Car.getprice (); }    //Total Car Sales     Public intGetmoney () {returnMoney ; }}
operating Result: Model: BMW Price:300000 Model: CHERYQQ Price:20000 total revenue:320000

Inheritance is the basis for the realization of polymorphism. Literally, polymorphism is a type (all car type) that shows a variety of states (BMW's name is BMW, the price is 300000; the name of the Chery car is cheryqq, the price is 2000). Associating a method call with the principal (that is, the object or Class) to which the method belongs is called binding, with two types of pre-and post-binding . Here's how they're defined:

1. Early binding: Binding before the program runs, implemented by the compiler and the linker, also called static binding. For example, the static method and the final method, note that this also includes the private method, because it is implicitly final.

2. Late binding: Binding according to the type of the object at run time, implemented by the method invocation mechanism, is also called dynamic binding, or run-time binding. All methods except pre-binding are late-bound.

Polymorphism is achieved on the mechanism of late binding. The benefit of polymorphism is that it eliminates the coupling between classes and makes the program easier to extend. For example, in the example above, a new type of car sales is added. Just let the newly defined class implement the car class and implement all its methods without any modification to the original code, and the Carshop class Sellcar (Carcar) method can handle the new model. The new code is as follows:

// Santana Car class Implements car{    public  String getName () {        return "Santana";    }      Public int GetPrice () {        return 80000;    }}

Thus, the definition of a class can be further improved:

 package   package name;  class  class name extends  parent class implements          interface name {member variable;        Construction method; member method;}  

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.