Java learning interfaces, polymorphism, and internal classes

Source: Internet
Author: User

An interface is a specification, a definition, of a set of behaviors. Interface is one of the essence of the object-oriented programming system, the use of interfaces can make our programs more conducive to change.

The format of the interface:

Interface interface Name {

global variables;

abstract methods;

}

The member modifiers in the interface are fixed, the member constants are modified with public static final, and the member functions are modified with public, and the appearance of the interface will be embodied by multiple implementations. The use of interfaces also have certain rules: interfaces can inherit multiple interfaces, a class can implement interfaces and multiple interfaces, the abstract class implementation interface can not implement the method, all the implementation methods in the interface access permissions are public; The properties defined in the interface are constants. Java uses the interface keyword to decorate the interface. When a method in an abstract class is abstract, the class can be represented in another way, that is, the interface.

1 Interface    demo{23public     static final  x=9; 4      Public  Abstract   void   Show ();56 }

Note: Classes and classes are inheritance relationships, and classes and interfaces are implementation relationships. An interface cannot be instantiated: only if the subclass of the interface is implemented and all methods in the interface are overwritten, the subclass can be instantiated, otherwise the subclass is an abstract class.

1 Interfaceanimal{2 String name;3 String age;4 5     Public voideat ();6    Public voidspeak ();7 8 }9 classcat{Ten  One     Public voideat () { ASystem. out. println ("I love to eat fish! "); -     } -  the  -      Public  voidspeak () { -System. out. println ("meow Meow ~~~"); -     } +}

The four main features of the interface: 1, the interface is the rule of external exposure, 2, the interface is the function of the expansion of programming, 3, the appearance of the interface reduces the coupling, 4, the interface can be used to implement more.

The similarities and differences between abstract classes and interfaces:

The same point: it is always drawn upward.

Different points: Abstract classes need to be inherited, and can only be single-inheritance, interfaces need to be implemented, can be implemented, abstract classes can be defined abstract methods and non-abstract methods, and interface can only define abstract methods, must be implemented by subclasses; the inheritance of abstract classes is a relationship, defining the basic common content of the system, The implementation of the interface is like a relationship, which defines the additional functions of the system.

What is an interface callback?

A reference to an object created by a class that implements an interface can be assigned to an interface variable declared by that interface, so that the interface variable can invoke methods in the interface that is implemented by the class.

Polymorphism: Polymorphism is one of the three main characteristics of object-oriented, the polypeptide is mainly embodied in two aspects: first, the method of overloading and rewriting. The second is the polymorphism of the object. Polymorphism is the multiple existence of a certain class of things.

For example: animals, cats, dogs

1. The cat type is the type of cat that corresponds to this object.

Cat X = new Cat ();

2, Cat is also a kind of animal, can also call the cat animal.

Animal Y = new Cat ();

A reference to the parent type points to the child class object. An object, two forms; a cat is a kind of thing that has the form of a cat and a form of an animal. This is the polymorphism of the object. In simple terms, an object corresponds to a different type. So what are the pros and cons of using polymorphism? Using polymorphism not only improves the extensibility of the code, but the code that is defined earlier can use later content. Of course, content that is defined in the pre-state using polymorphism cannot be used (called) for content that is specific to later subclasses.

Of course, the use of polymorphism also has a premise: the code must have a relationship, that is, inheritance or implementation, and the other is to have coverage (only on the function, the member variable is not).

Object polymorphism: The polymorphism of an object is derived from multiple classes in an inheritance relationship.

Transition up: Convert a subclass instance to a parent class instance

Format: Parent Class object = Subclass instance;------> Automatic Conversion

such as: int i= ' a '; Because Char has a smaller capacity than int, it can be done automatically.

Downward transformation: Converts the parent class instance into a subclass instance;

Format: Subclass Subclass Object = (subclass) Parent class instance;--------> Cast

For example: Char c= (char) 97, because the shaping of 4 bytes is larger than the char2 byte, it is forced to cast.

1 // For example 2 Animal  a=new  Cat ();   // automatic promotion, unique features not accessible 3 4 Cat  c= (cat)  A;   // The purpose of the downward transformation is to use the features that are unique in subclasses. 

Characteristics of polymorphism:

1), member variables:

At compile time, the referenced variable belongs to a class that has a calling member variable, has passed, does not fail, and, at run time, refers to the class in which the referenced variable belongs, and runs the member variable in the owning class.

Simply put: both compile and run refer to the left side of the equals sign.

2), member functions:

At compile time, the reference-referenced variable belongs to a class that has a calling member variable, has passed, has failed, and, at run time, refers to whether there are functions called in the class to which the object belongs.

Simply put: Compile and look to the left and run to the right.

3), static function:

At compile time, the referenced variable belongs to the class in which the calling static function is used. At run time, refer to whether the referenced variable belongs to the class in which the calling static function is used.

Simply put: Compile and run all look to the left. In fact, for static methods do not need the object, the direct class name can be called.

In polymorphism, there is also a keyword to note: instanceof keyword.

Syntax format: Object instanceof type------Returns a Boolean type value

This statement is generally used to determine whether an object is an instance of a class, returns True, or false.

Design rules for the parent class using the INSTANCEOF keyword:

With the instanceof keyword, we can check the type of the object, but how to set the parent class if there are too many subclasses in a parent class and the judgment is tedious?

1), the parent class is usually designed as an abstract class or interface, in which the interface is preferred and the interface is not satisfied before the abstract class is considered.

2), a collective class as far as possible not to inherit another specific class, the benefit is not to check whether the object is the parent class object.

1  Public  Static  voidmethod (Animal a) {2 a.eat ();3     if(a instance Cat) {4       //instance used to determine the specific type of object5       //usually the downward transition is used for robustness judgments. 6Cat c=(Cat) A;7 C.catchmouch ();8     }9}

Inner class: A class is defined inside another class, and the class inside is called an inner class (built-in class, nested Class). Internal class Access features: Inner classes can access members of external classes directly, including private members, and external classes must establish an object of the inner class to access the members of the inner class. You can create an inner class object externally: An inner class can be instantiated in addition to an external class by producing an instantiated object.

Method Inner class: An inner class can be a member of a class, and the class can be defined within a method.

The format of the members inner class:

1 classquter{2 3      Public  voidprint () {4       //instantiate an inner class object in an external class and invoke the method5Inner Inner =NewInner ("member inner Class");6 Inner. Print ();7     }8    classinner{}9 Ten}

Attention:

1), the method inner class can only be instantiated within a method that defines the inner class, and it cannot be instantiated outside of this method.

2), the method inner class object cannot use the non-final local variable of the method in which the inner class resides. An inner class can only access local variables that are final decorated locally.

Static Inner class:

The static meaning is that the inner class can, like other static members, have access to it when there is no external class object, and static nested classes can only access static members and methods of the outer class.

class quter{    static  class  inner{}         }class   test{       Public Static void   Main (string[] args) {       quter.inner n=new  Quter.inner ();}                        }

Features of internal class access:

1. The inner class can access the members of the external class directly. That's because the inner class holds references to external classes.

2, the external class to access the inner class, to establish an internal class object

When analyzing things, it is found that the transaction has something on the description, and that the thing is still accessing the content of the described thing, which is defined as an inner class.

classquter{PrivateString name;  Public voidShow () {} Public Static voidmethod () {}classinner{intAge ;  Public voidAddintAintb) {}         } Static classnner{ Public voidshou () {}Static voidfunction () {}}}classtest{ Public Static voidMain (string[] args) {//direct access to members in an external classQuter out=NewQuter ();  out. Show (); System. out. println ( out. Name); //direct access to members in an inner class in an external classQuter.innerinch=NewQuter ().NewInner (); inch. Show (); //if the inner class is static, it is equivalent to an external classQuter.nner inn=NewQuter.nner ();                       Inn.shou (); //if the inner class is static, the member is also staticQuter.Nner.function (); }}

Anonymous inner class:

An anonymous inner class is an inner class without a name, typically in three cases: 1) An anonymous inner class that inherits. 2) An anonymous inner class of an interface. 3) Anonymous inner class of the parametric type

An inherited anonymous inner class
New Thread () {
public void Run () {
for (int i = 1; I <= 5; i++) {
System.out.print (i + "");
}
}
}.start ();


//anonymous inner class of interface type Public voidPrint2 () {Child C=NewChild () { Public voiddesc () {System. out. println ("Interface Anonymous inner class"); } }}//anonymous inner class of the parameterized typeOuter.print3 (NewChild () { Public voiddesc () {System. out. println ("Anonymous internal class with parameters"); }});

Anonymous inner classes are shorthand for internal classes, with all the rules: that is, an inner class must inherit or implement an external class or interface.

Rules for using an anonymous inner class: there can be no constructors in an inner class, only one instance, no static members, no static methods, no modifiers public,protected,private,static; Inner classes must be behind new. Implement an interface with its implication or implement a class; The anonymous inner class is local, so all permissions for the local inner class take effect.

The role of anonymous inner classes: Each inner class can inherit independently from an implementation of an interface, so no matter whether an external class has inherited an implementation of (an interface), there is no effect on the inner class. An inner class provides the ability to inherit multiple concrete or abstract classes, and the inner class makes the scheme of multiple inheritance complete. The interface solves some problems, and the inner class solves the problem of multiple inheritance effectively.

Anonymous inner class usage scenario: When a function parameter is an interface type, and there are no more than three methods in the interface, the anonymous inner class can be passed as the actual parameter.

 Public  void   Method () {    Inner   in =new  Inner () {       public void   Show1 () {}        publicvoid  Show2 () {}         }    in . Show1 ();     inch

Java learning interfaces, polymorphism, and internal classes

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.