Object-oriented interfaces and Polymorphism

Source: Internet
Author: User

The interface is used to develop specifications so that subsequent programs can be implemented according to these specifications.

Interface declaration method: interface name {}. An interface can only declare an abstract method. At least one is required, but abstract modification is not required before declaring an abstract method.

Declare a class implementation interface, class demo implements interface_name {}. When a class implements an interface, this class must implement all the abstract methods defined in the interface. A class can inherit one class and implement multiple interfaces at the same time. Class demo2 extends demo implements interface1, interface2, interface3 {} must be prefixed.

Classes and classes can be inherited, interfaces and interfaces can also be inherited, interface1 extends interface2 {}.

If you want to implement a project or a complete function in an object-oriented way, first consider that this project or function involves several subjects (objects), and several subjects need to declare several classes, then, consider the attributes or methods of each subject. The work sequence and process between these subjects are usually one-ring.

Polymorphism: different objects call the same method or method with the same name to achieve different effects or functions. This is polymorphism. The usage of polymorphism is generally to declare a method with parameters in the class. The values received by this parameter are different objects and then call the method. For example:

Class demo {

Function demo (oarg ){

Oarg-> say ();

Oarg-> Run ();




Class test {

Suppose there are two classes A and B,

Function test1 (){

$ A = new;
$ B = new B;

$ Demo = new demo;

$ Demo-> demo ($ A); // both $ A and $ B call methods of the same name, say and run, but the say in Class A is different from the say and run in Class B. This is polymorphism.

$ Demo-> demo ($ B );



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.