Java Learning--basic knowledge advanced third day--interface, polymorphism

Source: Internet
Author: User
Tags modifier stub

Introduction of today's content

U interface

U polymorphic

1th Chapter Interface

1.1 Overview of interfaces

An interface is a collection of functions, which can also be seen as a data type, which is a more abstract class than an abstract class.

The interface only describes the methods that should be available, and there is no specific implementation, the implementation of the interface is implemented by the class (equivalent to the subclass of the interface) to complete. This separates the definition and implementation of the function and optimizes the program design.

1.2 Format & Use of interfaces

Format of the 1.2.1 interface

Unlike the class that defines classes, the interface keyword is required for the interface definition.

The definition of the interface is still a. java file, although a. class file is still generated after the compilation of the interface keyword that is used when declaring. This allows us to consider an interface as a special class that contains only functional declarations.

Define the format:

Public interface Interface Name {

Abstract Method 1;

Abstract Method 2;

Abstract Method 3;

}

Use of the 1.2.2 interface

Interface methods are all abstract methods, the direct new interface to invoke the method is meaningless, Java is not allowed to do so

The relationship of a class to an interface is to implement the relationship, that is, the class implements the interface. The implemented action is similar to inheritance, except that the keywords are different and implemented using implements

When the other class (Implementation Class) implements the interface, it is equivalent to declaring: "I should have the functionality in this interface." The implementation class still needs to override the method to implement the specific functionality.

Format:

Class implements interface {

Overriding methods in an interface

}

After the class implements the interface, the class inherits the abstract method from the interface, and the class needs to override the abstract method to complete the specific logic.

1.2.3 Case Code One:

Package com.itheima_01;

/*

* Java language inheritance is a single inheritance, a subclass can have only one parent class (a son can only have one father)

* The Java language provides us with a mechanism for handling inherited single limitations, interfaces

*

* Interface: interface is a class that is more abstract than abstract class, all the methods in the interface are abstract methods, interface and class relationship is implemented, implements

* Interface

*

Format

* Interface Interface Name {

*

* }

*

*/

public class Interfacedemo {

public static void Main (string[] args) {

BillGates gates = new BillGates ();

Gates.code ();

}

}

Class Boss {

public void Manage () {

SYSTEM.OUT.PRINTLN ("management Company");

}

}

Class Programmer {

public void code () {

System.out.println ("Knock Code");

}

}

Bill gates

Class BillGates extends Programmer {

}

1.3 Features of the members in the interface

1, the interface can be defined variables, but the variable must have a fixed modifier decoration, public static final so the variable in the interface is also called a constant, its value can not be changed. We'll explain the final keyword later.

2, the interface can be defined methods, methods also have fixed modifiers, public abstract

3. Interfaces are not available to create objects.

4, subclasses must overwrite all the abstract methods in the interface, subclasses can be instantiated. Otherwise, the subclass is an abstract class.

1.3.1 Case Code Two:

Package com.itheima_01;

/*

* Member features of the interface:

* There can only be abstract methods

* Can only have constants

* Default use of Public&abstract decoration method

* Only use the Public&abstract decoration method

* Use public static final to modify member variables by default

*

* Recommendation: We recommend that you manually give the default modifier

*

Note

* Interfaces cannot create objects (cannot be instantiated)

* Class-to-interface relationships are implementation relationships, and a class implements an interface that must implement all of its methods

*/

public class InterfaceDemo2 {

public static void Main (string[] args) {

Animal a = new Animal ();

Animal.num;

}

}

Interface Animal {

public static final int num = 10;

public abstract void Eat ();

}

Class Cat implements Animal {

public void Eat () {

}

}

1.4 Relationship of interfaces and classes

A: Between classes and classes: Inheritance, a class can inherit directly from only one parent class, but supports multiple inheritance

B: Between classes and interfaces: Only implementation relationships, one class can implement multiple interfaces

C: Between interface and interface: Only inheritance, an interface can inherit multiple interfaces

1.4.1 Case Code Three:

Package com.itheima_01;

/*

*

* Classes and classes: Inheritance relationships, single inheritance, multi-layer inheritance

* Classes and Interfaces: Implementing relationships, multiple implementations

* interface-to-interface relationships: Inheritance relationships, multiple inheritance

*/

public class InterfaceDemo3 {

public static void Main (string[] args) {

}

}

Interface Intera extends Interb {

public abstract void Method ();

}

Interface Interb {

public abstract void function ();

}

Interface Interc extends Intera {

}

Class Demo implements INTERC {

@Override

public void Method () {

TODO auto-generated Method Stub

}

@Override

public void function () {

TODO auto-generated Method Stub

}

}

1.5 The idea of the interface

Before learning the code embodiment of the interface, now to learn the idea of the interface, followed by the example of life in the description.

For example: We all know that there are many sockets on the computer, and these sockets can be plugged into the appropriate devices, why can they be plugged in? The main reason is that these devices conform to the usage rules of the socket when they are produced, otherwise they will not be able to be plugged into the interface or be unusable. Discover the presence of this socket and let us use more devices.

The appearance of the interface is convenient for later use and maintenance, one side is in the use of the interface (such as computer), a party in the implementation of the interface (plugged in the device). For example: Notebooks Use this rule (interface), computer peripherals implement this rule (interface).

Extensive use of interfaces in aggregate systems

Collection interface

List interface

ArrayList implementation Class

LinkedList Implementation Class

Set interface

1.6 Interface Benefits

1. The relationship between class and interface, implementation of the relationship, and is a multi-implementation, a class can implement multiple interfaces, class and class is an inheritance relationship, Java inheritance is a single inheritance, a class can have only one parent class, breaking the limitations of inheritance.

2. External provision of rules (USB interface)

3. Reduce the coupling of the program (can achieve modular development, define the rules, everyone to implement their own modules, improve the efficiency of development)

1.7 The difference between an interface and an abstract class

1. Commonality:

Continuous extraction, extraction of abstract, no concrete implementation of methods, can not be instantiated (cannot create objects)

2. Difference 1: Relationship with the class

(1) Class and interface is the implementation of the relationship, and is a multi-implementation, a class can implement multiple interfaces, class and abstract class is an inheritance relationship, Java inheritance is a single inheritance, multi-layer inheritance, a class can inherit only one parent class, but can have Grandpa class

(2) Difference 2: member

A. Member variables

Abstract classes can have member variables, or they can have constants

Interface can have constants only, default modifier public static final

B. Member methods

Abstract classes can have abstract methods, or they can have non-abstract methods

Interface can have abstract methods only, default modifier public abstract

C. Construction method

Abstract classes have construction methods that provide a subclass of

Interface has no construction method

1.8 Athlete Case

1.8.1 Case Code Four:

Package com.itheima_02;

/*

* Basketball players and coaches

Table tennis players and coaches

Now basketball players and coaches to go abroad to visit, need to learn English

Based on what you have learned, analyze what classes are, which are abstract, and which are interfaces.

*/

public class Interfacetest {

public static void Main (string[] args) {

Create a basketball player object

Basketballplayer BBP = new Basketballplayer ();

Bbp.name = "Female trillion month day";

Bbp.age = 35;

Bbp.gender = "male";

Bbp.sleep ();

Bbp.study ();

Bbp.speak ();

System.out.println ("-------------");

Create a table Tennis instructor object

Pingpangcoach PPC = new Pingpangcoach ();

Ppc.name = "Liu Fat";

Ppc.age = 40;

Ppc.gender = "male";

Ppc.sleep ();

Ppc.teach ();

Ppc.speak ();

}

}

Class Person {

String name;//Name

int age;//Age

String gender;//Sex

Non-parametric construction

Public person () {}

With a reference structure

Public person (String name,int age,string gender) {

THIS.name = name;

This.age = age;

This.gender = gender;

}

Eat

public void Eat () {

System.out.println ("eat");

}

Sleep

public void sleep () {

System.out.println ("Sleeping");

}

}

Learn to speak English

Interface Speakenglish {

public abstract void speak ();

}

Athletes

Abstract class Player extends person {

Learn

public abstract Void Study ();

}

Coach

Abstract class Coach extends person {

Teach

public abstract void teach ();

}

Basketball player

Class Basketballplayer extends Player implements speakenglish{

@Override

public void Study () {

System.out.println ("Learn to Dunk");

}

@Override

public void Speak () {

System.out.println ("speak English");

}

}

Table tennis player

Class Pingpangplayer extends Player {

@Override

public void Study () {

SYSTEM.OUT.PRINTLN ("Learning stroke");

}

}

Basketball coach

Class Basketballcoach extends Coach implements Speakenglish {

@Override

public void Teach () {

System.out.println ("Teaching dunk");

}

@Override

public void Speak () {

System.out.println ("speak English");

}

}

Table Tennis Coach

Class Pingpangcoach extends Coach {

@Override

public void Teach () {

System.out.println ("Teaching stroke");

}

}

The 2nd Chapter Polymorphic

2.1 Polymorphism Overview

Polymorphism is the third most characteristic of object-oriented after encapsulation and inheritance.

Real things often reflect a variety of forms, such as students, students are a kind of people, then a specific classmate Zhang San is a student is also a person, that appears two forms.

Java, as an object-oriented language, can also describe the various forms of a thing. If the student class inherits the person class, a student object is both student and person.

2.2 Definition and use of polymorphic formats

Polymorphic definition Format: Is the reference variable of the parent class pointing to the Child class object

Parent class type variable name = new subclass type ();

Variable name. Method name ();

A: Format of common polymorphic definitions

Parent class Variable name = new Subclass ();

such as: Class Fu {}

Class Zi extends Fu {}

Polymorphic Use of Classes

Fu f = new Zi ();

B: The format of the abstract class polymorphism definition

Abstract class Variable name = new abstract class subclass ();

such as: abstract class Fu {

public abstract void Method ();

}

Class Zi extends Fu {

public void Method () {

System.out.println ("Overriding the parent class abstract method");

}

}

Polymorphic Use of Classes

Fu fu= new Zi ();

C: The format of the interface polymorphism definition

Interface variable name = new Interface implementation class ();

such as: interface Fu {

public abstract void Method ();

}

Class Zi implements Fu {

public void Method () {

SYSTEM.OUT.PRINTLN ("Overriding interface Abstraction method");

}

}

Multi-state use of interfaces

Fu fu = new Zi ();

2.2.1 Case code Five:

Package com.itheima_01;

/*

* Prerequisites for polymorphism:

* Inheritance relationship of child parent class

* Methods of rewriting

* Parent class reference to child class object

*

* Dynamic Binding: The method that is called during the run is based on its specific type

*

*

*

*

*/

public class Poymorphicdemo {

public static void Main (string[] args) {

/*cat C = new Cat ();

C.eat (); */

Parent class Reference Animal a

Point to =

Subclass Object New Cat ()

Animal a = new Cat ();

A.eat ();

}

}

Class Animal {

public void Eat () {

System.out.println ("Eat something");

}

}

Class Cat extends Animal {

public void Eat () {

System.out.println ("Cat eats fish");

}

}

2.3 Characteristics of Polymorphic members

A: polymorphic member variables

When a member variable of the same name appears in the child parent class, when the variable is called by polymorphic:

Compile time: Refer to whether the referenced variable belongs to a class that has a called member variable. No, compilation failed.

Run time: is also a member variable in the class to which the reference variable belongs.

Simple: Compile and run all refer to the left side of the equals sign. Compile run look to the left.

B: Polymorphic Member method

Compile time: The reference variable belongs to the class, and if there are no methods called in the class, the compilation fails.

Run Time: Refer to the class to which the object refers to the reference variable, and run the member method in the class to which the object belongs.

In short: Compile to see the left, run to the right

2.3.1 Case Code VI:

Package com.itheima_01;

/*

*

* Characteristics of Polymorphic Members:

* Member variables are compiled to see the left side, run-time look at the left

* Member method compile-time look at the left, run-time look to the right

* Static method compile time to look at the left, the runtime is also looking at the left

*

*

* Compile-time look at the left, run-time member method to see the right side, other (member variables and static methods) look at the left

*

*/

public class PoymorphicDemo2 {

public static void Main (string[] args) {

Dad d = new Kid ();

System.out.println (D.num);

D.method ();

D.function ();//Use a variable to invoke a static method, which is actually equivalent to invoking the class name of the variable type

}

}

Class Dad {

int num = 20;

public void Method () {

System.out.println ("I am the Parent method");

}

public static void function () {

System.out.println ("I am a static method of the parent class");

}

}

Class Kid extends Dad {

int num = 10;

public void Method () {

System.out.println ("I am a subclass method");

}

public static void function () {

System.out.println ("I am a subclass static method");

}

}

2.4 Multi-state upward transformation and downward transformation

The transformation of polymorphism is divided into two types: upward transformation and downward transformation.

A: Upward transformation: When there are sub-class objects assigned to a parent class reference, is the upward transformation, polymorphism itself is the process of upward transformation.

Use format:

Parent class type variable name = new subclass type ();

such as: person p = new Student ();

B: A downward transition: a subclass object that has been transformed upward can use a format that enforces type conversions and converts a parent class reference to a subclass reference, which is a downward transformation. If the parent class object is created directly, it cannot be transformed downward.

Use format:

Subclass type variable name = (subclass type) A variable of the parent class type;

such as: Student stu = (Student) p; The variable p actually points to the student object

2.4.1 Case Code VII:

Package com.itheima_01;

/*

*

* Upward transformation and downward transformation in polymorphic:

*

* Conversions between reference types

* Upward transformation

* From small to large (subtype converted to parent type)

* Downward transformation

* FROM big to small

* Conversion of basic data types

* Automatic type conversion

* From small to large

* Byte short char---int---long---float---double

* Forced type conversion

* FROM big to small

*

*

*

*/

public class PoymorphicDemo3 {

public static void Main (string[] args) {

Animal2 a = new Dog ();//Upward transformation

A.eat ();

Dog d = (dog) a;//downward transition

D.swim ();

}

}

Class Animal2 {

public void Eat () {

System.out.println ("Eat something");

}

}

Class Dog extends Animal2 {

public void Eat () {

System.out.println ("Chew Bones");

}

public void swim () {

System.out.println ("Dog planing");

}

}

2.5 Advantages and disadvantages of polymorphism

2.5.1 Case Code Eight:

Package com.itheima_01;

/*

*

* Advantages and disadvantages of polymorphism

* Advantages: Can improve maintainability (guaranteed by multi-state premise), improve the extensibility of code

Disadvantage: You cannot directly access members that are specific to subclasses

*/

public class PoymorphicDemo4 {

public static void Main (string[] args) {

Mifactory factory = new Mifactory ();

Factory.createphone (New Minote ());

Factory.createphone (New RedMi ());

}

}

Class Mifactory {

/*public void Createphone (minote mi) {

Mi.call ();

}

public void Createphone (RedMi mi) {

Mi.call ();

}*/

public void Createphone (Phone p) {

P.call ();

}

}

Interface Phone {

public void call ();

}

Xiaomi note

Class Minote implements phone{

public void call () {

SYSTEM.OUT.PRINTLN ("Millet note call");

}

}

Red Rice

Class RedMi implements Phone {

public void call () {

System.out.println ("Red rice Phone");

}

}

Java Learning--basic knowledge advanced third day--interface, polymorphism

Related Article

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.