Javase Learning Summary (vi)--Interface and abstract class

Source: Internet
Author: User
Tags class definition iusb

Directory

    • I. Reasons for not needing to instantiate
    • I. Types that cannot be instantiated
    • Second, abstract class
    • Third, the interface
      • 3.1. Why interfaces are required
      • 3.2, the characteristics of the interface
    • Iv. Final (final)
      • 4.1. Final Modified Class
      • 4.2. Final Modification method
      • 4.3. Final modified variable
    • V. Video and sample download
    • Vi. Interview Questions
I. Reasons for not needing to instantiate

Look at an example:

Package com.zhangguo.chapter5.s1;/** Zoo */public class Zoo {public    static void Main (string[] args) {        Animal Animal=new animal ();        Animal.eat ();                /**new who Tune who * *        /**lsp*/        Animal dog=new Dog ();        Dog.eat ();    }} /** animal */class Animal {    /** eat */public    void Eat () {        System.out.println ("Animal Eats");}    } Class Cat extends animal{    /** rewrite eat * * public    void Eat () {        System.out.println ("Cat eats Fish");}    } Class Dog extends animal{    /** rewrite eat */public    void Eat () {        System.out.println ("Dog eats Bones");}    }

Results:

Problem:

As can be seen from the above example, animal is an abstract parent class, but in reality there is no real object called an animal, and the animal is merely an abstract concept.

In this case, animal should not be instantiated, only as a parent class, in object-oriented (OOP) types that serve this role are: abstract class, interface.

Abstract classes and interfaces are types that are more abstract than classes.

I. Types that cannot be instantiated

From the above concept, it can be learned that some types should not be instantiated and meaningless.

Abstract classes in Java are more conducive to the maintenance and reuse of code.

1. Because an abstract class cannot instantiate an object, you must have a subclass to implement it before you can use it. This allows you to abstract some components with the same properties and methods, which is more advantageous for code and program maintenance.

2. When a similar component is created, only the abstract class can be implemented to obtain those properties and methods of the abstract class.

Abstract classes are primarily used for type concealment in object-oriented methods. Constructs an abstract description of a fixed set of behaviors, but this group of behaviors can have any possible concrete implementation. This abstract description is an abstract class, and any possible concrete implementation of this group is represented by all possible derived classes. The module can manipulate an abstract body. Because the module relies on a fixed abstraction, it can be modified, and the behavior of this module can be extended by deriving from this abstraction. Abstract classes are the key to achieving a core principle OCP (open-closed Principle) for object-oriented design.

(1), interface

(2), abstract class

(3), the access rights of the construction method are private

Package com.zhangguo.chapter5.s1;/** Eat interface */interface ieatable {    void Eat ();} /** Animal Abstract class */abstract class Animal {    /** Eat abstract method *    /public abstract void Eat ();} /** students General class */class Student {    /** Private construction method *    /Private Student () {    }}public class Noinstance {public    static V OID Main (string[] args) {        ieatable obj1 = new ieatable ();//error cannot instantiate interface        Animal obj2 = new Animal ();//error cannot instantiate abstract class        Student obj3 = new Student ();//error cannot instantiate private construction method class    }}

In some languages, static classes cannot be instantiated, such as C #

Meaning: The more abstract, the more stable. Abstract can define the upper structure, standardize the top-level design. Abstractions do not and should not change at random.

Second, abstract class

2.1. Syntax definition

Abstract class definition, which is an abstract class, before an abstract class is decorated with an abstract keyword.

2.2. Use

A, in some cases, a parent class just knows what the subclass should contain, but it doesn't know exactly how these subclasses implement these methods
(Abstract class constraints subclasses must have methods, but they are not concerned with how subclasses implement these methods.) )

b, from a number of classes with the same characteristics abstract an abstract class, the abstract class as a subclass of the template, so as to avoid the arbitrary design of sub-class.

2.3. Significance

Restriction subclasses must implement some methods, but do not pay attention to implementation details.

2.4. Features

1, abstract methods must be in the abstract class

2, both abstract methods and abstract classes must be decorated with the abstract keyword

3, abstract classes can not create objects with new. Because invoking abstract methods does not make sense 4, abstract methods in the abstract class to be used, the subclass must be replicated all the abstract methods after the child class object call.

If a subclass overrides only a subset of the abstract methods, then the subclass is an abstract class.

5. Abstract method without method body, end with semicolon

Example:

Package Com.zhangguo.chapter5.s2;import java.util.scanner;/** Animal */public abstract class Animal {    /** name *    / public String name;    /** abstract method, no method body, the quilt class must be implemented (rewritten) */public    abstract void Eat ();        /** Test */public    static void Main (string[] args) {        //lsp richter replacement principle        Animal dog=new Dog ();        Dog.name= "Bo Mei";        int i=1;        Scanner input=new Scanner (system.in);        Dog.eat ();    }        /** Abstract classes can have non-abstract methods, there can be static methods *    /public void Show () {};} /** the subclass of an abstract class animal (Animal), you must implement a method that is not implemented by the parent class */class Dog extends Animal {    //annotation    @Override public    void Eat () {        System.out.println (this.name+ "Dog is eating Bones");}    }

Operation Result:

Third, the interface

An interface is a set of standards and specifications without instances.

What is a computer without an interface?

3.1. Why interfaces are required

Inheritance: Describes the natural properties of things and the reuse of behaviors.

Interface: Describes the social properties and the reuse of the behavior of a thing.

1. Importance: In the Java language, abstract classes and interface are the two mechanisms that support the definition of a class of abstractions. It is the existence of these two mechanisms that gives Java a powerful object-oriented capability.

2, simple, normative: If a project is large, then you need an architect who can clear all the business to define some of the main interfaces, these interfaces not only tell the developers you need to implement those business, but also the naming specification is limited (to prevent some developers can not see the name of the other programmers do not understand).

3, Maintenance, Expansion: For example, you want to do an artboard program, which has a panel class, mainly responsible for painting functions, and then you define this class.

4, security, tightness: interface is an important means of software loose coupling, it describes all the services of the system outside, and does not involve any specific implementation details. This is more secure, more rigorous (the General software service providers consider more).

Because a class has a "single root", all classes can have only one direct parent class, and multiple inheritance is possible by implementing a class that has more than one parent class.

Package Com.zhangguo.chapter5.s2;/**usb Interface */public interface Iusb {    /** not implemented method, send data *    /void SendData ();} /** Cable Interface */interface irj45{    /** Not implemented method, receive data *    /void Receivedata ();} /** device */class device{    }/** computer *//** A class can inherit only one class, but it is possible to implement multiple interfaces */class computer extends Device implements iusb,irj45{    @ Override public    void Receivedata () {        System.out.println ("Receive data");    }    @Override public    void SendData () {        System.out.println ("Send data");    }            Interface ia{}    interface ib{}    /** interface can inherit other he/    interface IC extends ia,ib{}        class cc{}    /** Inheritance needs to be written before implementing interface */    class DD extends CC implements IC {}}

Test:

Package Com.zhangguo.chapter5.s2;public class Computerclient {public    static void Main (string[] args) {        Computer ln=new computer ();        Ln.senddata ();        Ln.receivedata ();                /** interface is a type *        /IUSB usb=new computer ();                /** An object can have several different types of */            }}

3.2, the characteristics of the interface

1), the method in the interface can have parameter list and return type, but cannot have any method body.

2), the interface can contain fields, but they are implicitly declared static and final.

3), the field in the interface is stored only in the static storage area of the interface, not the interface.

4), the method in the interface can be declared public or not declared, but the result will be treated according to the public type.

5), when implementing an interface, the defined method needs to be declared as public type, otherwise the default access type, the Java compiler does not allow this situation.

6), if you do not implement all the methods in the interface, then the creation is still an interface. Subclasses must implement methods that are not implemented in the interface, unless subclasses are also interfaces.

7), extending an interface to generate a new interface should use the keyword extends to implement an interface using implements.

8), the method in the interface is abstract method (abstract), can not be static method (static), all the methods of the interface are abstract, and the abstract method is not static, there is static method is not override, so it is meaningful to define the interface.

The field in the interface is the default: Static final, which is commonly said to be constant

Final (final) 4.1, Final modified class

The final decorated class is not allowed to be inherited.

A class cannot be both final and abstract. Because the primary purpose of abstract is to define a convention that allows subclasses to implement such conventions, and final indicates that the class cannot be inherited, and that the two contradictions.

4.2. Final Modification method

The final decoration method, which indicates that the method cannot overwrite the override with a method in the quilt class. Cannot be rewritten

4.3. Final modified variable

The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.

When final modifies a native data type, the value representing the native data type cannot be changed;

If final modifies a reference type, it means that the reference type cannot point to another object, but the contents of the object to which the reference is pointing can change.

is essentially one thing, because the value of the reference is an address, the final requirement value, that is, the value of the address does not change.

Final modifies a member variable (property) that must be displayed for initialization.

There are two types of initialization, one is initialized at the time of the variable declaration, and the second is to not assign the initial value when declaring the variable, but to assign an initial value to the variable in all the constructors of the class where the variable resides.

When the parameter type of a function is declared final, the parameter is read-only.

V. Video and sample download

Class Sample Download

B Station Video online watch

Vi. Interview Questions

1. Are there types that cannot be instantiated in Java?

2. What are the characteristics of abstract classes?

3. What are the features of the interface?

Javase Learning Summary (vi)--Interface and abstract class

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.