JAVA interfaces and Polymorphism

Source: Internet
Author: User

Interface

It can be understood as a special class, which is composed of global constants (static final) and public abstract methods.

Interface Definition Format

The data member of the API can only be modified by public, static, and final.
Method Member of the API, which can only be modified by public and abstract.
Interface name {
Private static final int var1 = 1; // error

Public static final int var2 = 2;

Public abstract void fun1 ();

Private abstract int fun2 (); // error.

}
 
All data members in the interface are of the static final type and must be initialized. The value of the data member of the interface cannot be modified. The static and final keywords can be omitted.
The methods in the interface must be "abstract methods" and cannot have method bodies. public and abstract keywords can be omitted.
Public interface {
Int num; // error. Not initialized
String name = "test ";
Public void getName (){......} // Error. The method body cannot be defined.
}
 
Interface implementation
Interfaces cannot use the new operator to directly generate objects. They must use their features to design new classes and use new classes to create objects.
Like an abstract class, an interface must also be used through a subclass. A subclass uses the implements keyword to implement an interface.
Implementation format:
Class subclass name implements interface A, interface B ,.... {
// Subclass member declaration
}
The use of interfaces must pass through subclass, And the subclass must overwrite all abstract methods. Although a subclass can only inherit one parent class, it can implement multiple interfaces at the same time.
Interface {
Public String name = "James ";

Public void print ();

Public String getName ();

}
Interface B {
Public void setName ();

}
Class C implements A, B {
Public void print (){......};

Public String getName (){......};

Public void setName (){......};

}
 

All methods in the interface must be implemented. Otherwise, the class implementing the interface will have abstract methods, so it becomes an abstract class.
When overwriting methods from interfaces, it must be declared as public.
Class C implements A, B {
// Public void print (){......}; // The print method is not overwritten. The compilation is not complete.

Public String getName (){......};

Public void setName (){......};

}
 

Object Transformation

An object can be transformed into an interface type implemented by its class.
The interface cannot be instantiated through new, but the interface variables can be declared.
Public class Test implements {

Intidx = 1;

Public void print (){

System. out. println ("")

}

Public String getName (){

}

Public static void main (String [] agrs ){

Test test = new Test ();

A a = (A) test; // The object is converted to the interface type

System. out. println (a. name); // output the name value

A. idx = 2; // error. idx belongs to test and does not exist in interface.

A. print (); // execute the print method of Test.

}

}

 

Inherited abstract class implementation Interface

A subclass can inherit abstract classes and interfaces at the same time.
The format is as follows:
Class subclass extends abstract class implements interface A, interface B ,...... {}
 

Interface inheritance

An interface cannot inherit from an abstract class, but can inherit from multiple interfaces at the same time through extends.
Public abstract class base {......}
Interface B {......}
Interface C {......}
Interface A extends base {......} // Error
Interface A extends B, C {......} // Correct
 

Differences between interfaces and inheritance

No.
Differences
Abstract class
Interface
 
1
Definition
Abstract Declaration: abstract methods are optional.
It is declared as an interface and consists of static constants and abstract methods.
 
2
Composition
Constructor, abstract method, common method, constant, variable
Static constants and abstract methods
 
3
Use
Subclass inheritance abstract class (extends)
Sub-class implementation interface (implements)
 
4
Link
Abstract classes can implement multiple interfaces
An interface cannot inherit abstract classes, but multiple interfaces can be inherited.
 
5
Object
All produce instantiated objects through object Polymorphism
 
6
Limitations
Abstract classes have limitations of single inheritance
Interface can implement multiple inheritance
 
7
Select
If both abstract classes and interfaces can be used, the interface is preferred to avoid the limitations of single inheritance.
 


 

Polymorphism

Different types of objects can respond to the same message. Multiple types derived from the same base class can be treated as the same type, the same processing can be performed on these different types. Due to polymorphism, the behavior of these derived class objects in response to the same method is different.
For example
-All objects of the Object class respond to the toString () method.
There are two types of polymorphism in java:
Reload and override of the rewrite Method
Polymorphism of the primary object
 
Object Polymorphism
There are two types of object polymorphism:
Upward transition: subclass Object> parent class Object
For the upstream transformation, the program will automatically complete.
Parent // BaseClass is the parent class, And DerivedClass is the derived class of BaseClass
Export BaseClassbc = new DerivedClass (); // implicit transformation.
Downward transition: parent class Object> subclass object
For downward transformation, the subclass type to be transformed must be clearly specified.
Export BaseClassbc = new DerivedClass (); // first transforms upwards
Extends DerivedClass dc = (DerivedClass) bc;
 

Public class {

String name = "";

Public void fun1 (){

System. out. println ("A-> fun1 ");

}

Public void fun2 (){

System. out. println ("A-> fun2 ");

}

}

Public class B extends {

String name = "B ";

Public void fun1 (){

System. out. println ("B-> fun1 ");

}

Public void fun3 (){

System. out. println ("B-> fun3 ");

}

}

Upward Transformation:

Public class Demo {

Public static void main (String args []) {

A a = new B ();

A. fun1 (); // What is output? B-> fun1

A. fun2 (); // What is output? A-> fun2

A. fun3 (); // The fun3 method is not defined in error..

System. out. println (a. name); // What is output?

}

}

 

Downward Transformation
Public class Demo {

Public static void main (String args []) {

// B B B = (B) new A (); // force transformation, throwing an exception after running

A a = new B ();

B B B = (B) a; // downward Transformation

B. fun1 (); // What is output? A-> fun1

B. fun2 (); // What is output? A-> fun2

B. fun3 (); // What is output? B-> fun3

}

}

In order to generate A downward transformation of objects, an upward transformation relationship must first be generated. a A = new B (); indicates establishing a relationship.
 

Objective of Polymorphism

All objects can be converted to the same type and respond to the same message.
Make the code simple and easy to understand
Make the program have good "scalability"
 

Application Instance

Technical Basis
Transform upward: The referenced variable of a parent class can point to different subclass objects.
Dynamic binding: During the runtime, the corresponding subclass method is executed based on the actual type of the object referenced by the parent class to realize polymorphism.
Example 1: Driver Driving
Public abstract class Driver {

Public Driver (){}

Public abstract void drives ();

}

Public class FemaleDriver extends Driver {

Public FemaleDriver (){}

Public void drives (){

System. out. println ("A Female driver drives a vehicle .");

}

}

Public class MaleDriver extends Driver {

Public MaleDriver (){}

Public void drives (){

System. out. println ("A Male driver drives a vehicle .");

}

}

 

Public class Test {

Public static void main (String [] args ){

Driver a = new FemaleDriver ();

Driver B = new MaleDriver ();

A. drives ();

B. drives ();

}

}

Output result: A Female driver drives a vehicle.

A Male driver drives a vehicle.

 

Example 2: What is the driver driving?
The practice of not using object Polymorphism
Public class MaleDriver extends Driver {

Public MaleDriver (){}

Public void drivesBus (){

System. out. println ("A Male driver drives a bus .");

}

Public void drivesCar (){

System. out. println ("A Male driver drives a car .");

}

Public void drivesTruck (){

System. out. println ("A Male driver drives a truck .");

}

......

}

 

Exploitation of object Polymorphism
Public abstract class Vehicle {
Public void drivedByFemale ();
Public void drivedByMale ();
}
Public class Bus extends Vehicle {
Public void drivedByFemale (){
System. out. println ("A Female driver drives a bus .");
}
Public void drivedByMale (){
System. out. println ("A Male driver drives a bus .");
}
}
 

Public class MaleDriver extends Driver {
Public void drives (Vehicle v ){
V. drivedByMale ();
}
}
Public class Test {
Public static void main (){
Vehicle bus = new Bus ();
Driver male = new MaleDriver ();
Male. drives (bus );
}
}
Output result: A Male driver drives a bus

 

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.