Java learning notes 8 -- interface summary, java learning notes 8 --

Source: Internet
Author: User

Java learning notes 8 -- interface summary, java learning notes 8 --

Next, we learned the following:

Java study notes 7 -- abstract classes and abstract methods

Java study Note 6-class inheritance, Object class

Java study notes 5-Class Method

Java study note 4-object initialization and collection

Java Study Notes 3-Basics of classes and objects

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note8.html.

Interfaces in life:

What is an interface?

A Java interface is a collection of methods and features, but there is no method implementation.

You can use the keyword implements to implement interfaces in the class. The basic format is as follows:

[Modifier] class <class Name> [extends parent class name] [implements interface list] {
}
Modifier:Optional parameter, used to specify the class access permissions. Optional values: public, abstract, and final.

Class Name:Required parameter. It is used to specify the name of a class. The class name must be a valid Java identifier. Generally, uppercase letters are required.

Extends parent class name: Optional parameter, used to specify the parent class that the class to be defined inherits from. When the extends keyword is used, the parent class name is a required parameter.

Implements interface list:Optional parameter, used to specify the interfaces implemented by this class. When the implements keyword is used, the interface list is a required parameter. When multiple interface names exist in the interface list, each interface name is separated by a comma.

Implement the interface in the preceding example:

Public interface PCI {// java interface, equivalent to the specification of the PCI slot on the motherboard public void start (); public void stop ();}

The methods defined in the Java interface are implemented in different places and can have completely different behaviors:

// The Sound Card and nic all implement the PCI slot specification, but the behavior is completely different class SoundCard implements PCI {public void start () {System. out. println ("SoundCard start... ");} public void stop () {System. out. println ("Sound stop! ") ;}} Class NetworkCard implements PCI {public void start () {System. out. println ("NetworkCard send... ");} public void stop () {System. out. println ("Send stop! ");}}

You can use the Java interface to identify the type. During running, call the corresponding method implementation based on the actual object type:

public class javatest {    public static void main(String[] args) {        PCI nc = new NetworkCard();        PCI sc = new SoundCard();        nc.start();        sc.start();    }}

Running result:

NetworkCard send...
SoundCard start...

Why Java interfaces?

For example, a small system is developed for each school center, including instructors, centers, and printers. The specific requirements are as follows:

1. Instructors and centres all have methods: Output detailed information

2. The center has properties: The printer can print the instructor or center details through the central printer

3. The system must have good scalability and maintainability.

First look at solution 1:

Public class Teacher {// output instructor details public String detail () {return "I am a teacher! ";}} Public class Printer {public void print (String content) {System. out. println ("start printing:"); System. out. println (content) ;}} public class ggSchool {private Printer printer = new Printer (); // output school details public String detail () {return "this is ggSchool" ;}// print instructor information public void print (Teacher t) {printer. print (t. detail ();} // print the school information using a printer public void print (ggSchool s) {printer. print (s. detail ());}}

So the question is:

Each new type requires a corresponding print method. The scalability and maintainability of the program are very poor, which does not meet the requirements of the system.

First look at solution 2 (using the interface ):

Both teachers and centers share a common method feature: detail, which has different implementations for the detail method. This fully complies with the definition of the Java interface.

The Code is as follows:

Public interface Introduceable {public String detail ();} public class Teacher implements Introduceable {// output instructor details public String detail () {return "I am a teacher! ";}} Public class ggSchool implements Introduceable {private Printer printer = new Printer (); // output the school's detailed information public String detail () {return" this is ggSchool ";} public void print (Introduceable intro) {// when the print method is used, the parameter can be an object of any implementation class of the Introduceable interface, // you do not have to create printer for different print methods for different types. print (intro. detail () ;}} public class Printer {public void print (String content) {System. out. println ("start printing:"); System. out. println (content );}}

Through the Java interface, we can also enjoy the benefits of polymorphism, greatly improving the scalability and maintainability of the program.

What is interface-oriented programming?

During system development, the main architecture uses interfaces to form the skeleton of the system. In this way, you can replace the system implementation by replacing the implementation class of the interface.

Upgrade the above system. Requirements:

There are multiple types of printers, such as black and white printers and color printers.

The school may be equipped with any of the printers responsible for printing instructor or school details

The system must have good scalability and maintainability.

Step 1: abstract the Java Interface

1. Analysis:

Both black and white and color printers share a common feature: print

Print methods are different for black/white and color printers.

2. Conclusion:

Abstract The Java interface PrinterFace and define the print method in it.

3. Specific implementation:

public interface PrinterFace {       public void print(String content);}
Step 2: Implement Java Interfaces

1. Analysis:

Java interface PrinterFace has been abstracted, and the print method black and white and the color printer have different implementations for the print method.

2. Conclusion: Both the black and white printer and the color printer implement the PrinterFace and print method respectively.

3. Specific implementation:

Public class ColorPrinter implements PrinterFace {public void print (String content) {System. out. println ("color print:"); System. out. println (content) ;}} public class BlackPrinter implements PrinterFace {public void print (String content) {System. out. println ("black/white print:"); System. out. println (content );}}

Step 3: Use the Java Interface

1. analysis: the main architecture uses interfaces to make interfaces constitute the skeleton of the system.

2. Conclusion: You can replace the system implementation with the class that implements the interface.

3. Specific implementation:

Public class ggSchool implements Introduceable {private PrinterFace printer; // printer public void setPrinter (PrinterFace p) {this. printer = p;} public String detail () {return "this is ggSchool! ";} Public void print (Introduceable intro) {printer. print (intro. detail () ;}} public class Test {public static void main (String [] args) {// create a school instance ggSchool school = new ggSchool (); // The school is equipped with a black-and-white printer. setPrinter (new BlackPrinter (); school. print (school); // The school is equipped with a color printer school. setPrinter (new ColorPrinter (); school. print (school );}}
Abstract classes and interfaces

The subclass of an abstract class must overwrite all abstract methods before it can be instantiated. Otherwise, this subclass is still an abstract class.

If all methods in an abstract class are abstract, you can define this class in another way, that is, interface definition.

Abstract METHODS only need to be declared and need not be implemented.

An interface is a set of definitions of abstract methods and constant values.

In essence, an interface is a special abstract class. This abstract class contains the definition of constants and methods without the implementation of variables and methods. For example

Note: In the interface definition, all Members are of the public access type, regardless of whether or not they are modified with the public keyword. the variables in the interface are identified with the public static final. Therefore, the variables defined in the interface are global static.

Constant.

We can define a new interface and use the extends keyword to inherit an existing interface. Note: Only interfaces can inherit interfaces, and classes cannot inherit interfaces.

A class can only use the implements keyword to implement all methods in an interface.

A class can implement one or more interfaces while inheriting a parent class. The extends keyword must be before the implements keyword, as can be defined as follows:

class classA {    //...}public interface Interface1{    //...}public interface Interface2{    //...}class classB extends classA implements Interface1 Interface2{    //...}
Application of abstract classes and interfaces in Java

Example: Suppose there are several (for example, 1000) Circle, Rectangle, and several other shapes to calculate their total area, the straightforward way is to put them in multiple arrays, this method is not beautiful. If there are other shapes: triangle, ellipses, etc., the above method is "cumbersome ". We hope to have a unified representation, such as using an array shape [] to accept all shapes, and then using:

 for (i=0; i<shape.length; i++)        area_total += shape[i].area();

Abstract classes are used to accumulate various shapes and areas:

First, let's take a look at the Circle and Rectangle classes and how to complete the calculation of related parameters:

class Circle {    public float r;     Circle(float r) {          this.r = r;          }    public float area() {        return 3.14 * r * r;    }}class Rectangle {    public float width, height;     Rectangle (float w, float h) {        width = w;         height = h;    }    public float area() {        return width * height;    }}

Abstract classes are used to accumulate various shapes and areas to ensure that each shape uses different methods to calculate their area and perimeter. Therefore, a superclass Shape contains the abstract method computeArea, which is then implemented and overwritten in different subclasses, And the toString method is added to display some basic attributes of the geometric Shape. Now we declare an array of 1000 Shape objects, and then generate 1000 flat graphics objects at random for 1000 cycles. The shapes are circle, rectangle, and square.

Abstract class Shape {abstract float computeArea ();} class Circle extends Shape {public float r; public Circle (float r) {this. r = r ;}public float computeArea () {return (float) 3.14 * r ;}} class Rectangle extends Shape {public float width, height; Rectangle (float w, float h) {width = w; // this does not need to be "this" height = h;} public float computeArea () {return width * height ;}}

Use interfaces to accumulate various shapes and areas:

To accumulate multiple shapes and areas by using interfaces, you need to change the Shape class represented by abstract classes to interfaces. Due to the syntax definition requirements of the interface, we need to remove the member variables in the original abstract class and change the member Method to the abstract method computeArea (). This method returns a double type. Therefore, this interface is defined:

public interface Shape2 {       public abstract double computeArea();}

The interface implementation is as follows:

interface Shape2{      public double computeArea();}class Circle2 implements Shape2{    protected double radius;    public Circle2(double _radius) {        radius = _radius;    }    public double computeArea() {         return Math.PI * radius * radius;     }}class Rect2 implements Shape2{      protected double width, height;    public Rect2(double w, double h) {          width = w;        height = h;    }    public double computeArea() {           return width * height;      }}

Using an array of objects to accumulate areas of multiple shapes:

Defines an array that can store rectangles, circles, and squares at the same time. Each Java class is extended by objects. Therefore, all classes belong to the Object type. We can create an array of the Object type to store any type of objects. In this way, we can store rectangle, circle, and square objects.

The complete code is as follows:

package javatest;import java.util.*;import java.io.*;interface Shape2 {      public double computeArea();}class Circle2 implements Shape2 {     protected double radius;     public Circle2(double _radius) {         radius = _radius;     }     public double computeArea() {          return Math.PI * radius * radius;      }}class Rect2 implements Shape2 {      protected double width, height;    public Rect2(double w, double h) {          width = w;        height = h;    }    public double computeArea() {           return width * height;      }}public class javatest {      public static void main(String args[ ]) {           Shape2 s[] = { new Circle2(4),  new Rect2(4, 4),                          new Circle2(10),  new Rect2(20, 2), new Rect2(8, 10)          };          double total = 0;          for(int i = 0; i < s.length; i++)              total = total + s[i].computeArea();          System.out.println("totalArea = " + (int)total);            }}
References

Java interface handout-siyuan College

Java course handout-computer College of Donghua University

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.