Java beauty [from cainiao to master Evolution] and objects (2)

Source: Internet
Author: User

Abstract classes, interfaces, and internal classes of classes and objects

Author: Egg

Weibo: http://weibo.com/xtfggef

Source: http://blog.csdn.net/zhangerqing

Abstract classes and interfaces:

These two concepts are always discussed together, because they have many similarities. It can be said that the interface itself is completely abstract, and it is more "abstract" than the abstract class. Why? Abstract classes are a type. In addition to abstract methods, they can also have specific methods. Interfaces must be abstract methods (classes can be defined in interfaces and will be discussed later ), although it is sometimes not displayed, it is declared with the abstract keyword. Abstract methods are mentioned here. in Java, all methods declared as abstract void function () are abstract methods. Classes containing abstract methods are abstract classes. This can be summarized as follows: abstract classes can have no abstract methods. classes with abstract methods must be abstract classes. abstract classes do not necessarily have entity methods.

public class B extends A {@Overridevoid a() {System.out.println();}}abstract class A {abstract void a();void b(){}}

When we inherit an abstract class, we must override its abstract method. Because of the above reasons, the abstract class cannot be declared as the final type, because the class with the final keyword cannot be inherited, so the class cannot be used when the final keyword is added to the abstract class. Abstract classes can only be inherited and cannot be instantiated!

Classes declared as interfaces are interfaces, which are more abstract than abstract classes. In an interface, we cannot provide any implementation. All methods must be abstract without abstract keywords. However, the compiler directly processes methods in the interface according to abstract methods. We use implements to implement an interface. When we implement an interface, we must override all its methods.

Java multi-Inheritance

Previously, we knew that using interfaces provides us with a structured method to separate abstraction from implementation. However, interfaces are far more effective than that, in Java, the interface solves a very important problem: Multi-inheritance. In C ++, implementing multi-inheritance is simple, but the Java Inheritance mechanism does not allow multi-inheritance. Therefore, if you want to integrate the functions of different classes, you need to use interfaces, let's look at an example:

interface CanFight {void fight();}interface CanFly {void fly();}interface CanSwim {void swim();}class ActionCharacter {public void fight(){}}class Hero extends ActionCharacter implements CanFight, CanFly, CanSwim {@Overridepublic void swim() {}@Overridepublic void fly() {}}public class Adventure {public static void t(CanFight x){x.fight();}public static void u(CanSwim x){x.swim();}public static void v(CanFly x){x.fly();}public static void w(ActionCharacter x){x.fight();}public static void main(String[] args) {Hero h = new Hero();t(h);u(h);v(h);w(h);}}

We can see that:

1. Hero class has all the functions of the class.

2. Hero can convert each other with the interfaces implemented by hero. When we make hero objects as parameters and pass them into various methods of the adventure class, the Hero class is transformed upwards. (Here we come up with a sentence: in Java, the interface can be converted to the class that implements the interface ). Here, I would like to summarize the advantages of using interfaces:

1. interfaces can achieve Upward transformation. Multiple classes with common attributes can extract their commonalities and make them abstract. In this way, they are well-defined and managed in a unified manner.

2. interfaces are not implemented in any way and are most suitable for base classes.

Summarize the differences between abstract classes and interfaces:

A) abstract classes are classes and can have entity methods.

B) abstract classes cannot implement multi-inheritance, but interfaces can.

C) if you need to create a base class without any method definition or member variables, use the interface. If you need some specific implementation in the class, use the abstract class.

D) If you want to design a class as a base class in advance, the interface is preferred. (Note that C and D are the use cases of interfaces.)

Interfaces can be extended through the extends interface. The fields in the interface are final and static by default, which can be directly referenced by class names.
Internal class

Create:An internal class refers to placing the class definition inside another class. Sometimes reasonable use of internal classes can make the code more concise and make the program more clever. As a member of the external class, the internal class can access the private member variables of the external class. Let's take a look at the creation of internal classes in the following situations:

1. Create an internal class instance in a non-static method of the external class.

public class InnerClass {class A{int a = 10;void b(){System.out.println("this is A.b()!");}}void build(){A a = new A();a.b();}public static void main(String[] args) {InnerClass ic = new InnerClass();ic.build();}}

2. Create an internal class instance in the static method of the external class.

When an internal class is created in the static method of the external class, the internal class is static:

public class InnerClass {static class A{int a = 10;void b(){System.out.println("this is A.b()!");}}public static void main(String[] args) {InnerClass.build();}static void build(){A a = new A();a.b();}}

When the internal class is non-static:

public class InnerClass {class A{int a = 10;void b(){System.out.println("this is A.b()!");}}public static void main(String[] args) {InnerClass ic = new InnerClass();InnerClass.A aa = ic.new A();aa.b();}}

3. Create an external class instance in the non-static method of the internal class. (Use external class. This to create an external class instance)

public class InnerClass {class A{int a = 10;void build(){InnerClass ic = InnerClass.this;ic.a();}}void a(){System.out.println("this is InnerClass.a()!");}}

4. Create an external class instance in the static method of the internal class. (Create directly through new)

public class InnerClass {static class A{int a = 10;static void build(){InnerClass ic = new InnerClass();ic.a();}}void a(){System.out.println("this is InnerClass.a()!");}}

5. Create an internal class instance in another class. (Important)

Public class innerclass {Class A {void a () {system. Out. println ("This Is A. ()! ") ;}} Static class c {void C () {system. Out. println (" This is C. C ()! ") ;}} Class B {public static void main (string [] ARGs) {/* create a non-static internal class */innerclass Ic = new innerclass (); a A = IC. new A ();. A ();/* Create a static internal class */C = new C (); C. C ();}}

Let's look at a deep nested:

public class ABC {void a() {System.out.println("this is A.a()!");}class B {void b() {System.out.println("this is B.b()!");}class C {void c() {a();b();System.out.println("this is C.c()!");}}}public static void main(String[] args) {ABC abc = new ABC();ABC.B b = abc.new B();ABC.B.C c = b.new C();c.c();}}

It's getting more and more interesting! The most important thing here is the ". New" operator. At the same time, it is easy to call both a () and B () in Class C, which means that the internal class is equivalent to a common variable, even with the private permission, directly called because they are in the same class. Create an anonymous internal class:

interface A {void a();}public class InnerClass_NoName {public A test() {return new A() {public void a() {System.out.println("");}};}public static void main(String[] args) {InnerClass_NoName icn = new InnerClass_NoName();A a = icn.test();a.a();}}

Typically, an internal class inherits from a class or implements an interface, and the code operation of the internal class creates its peripheral class object. So you can think that the internal class provides a window for entering its peripheral class. The most attractive reason for using internal classes is that each internal class can independently inherit from one (Interface) implementation, so no matter whether the peripheral class has inherited an (Interface) implementation, internal classes are not affected. Without the ability of internal classes to inherit multiple specific or abstract classes, it is difficult to solve some design and programming problems. From this perspective, the internal class makes the multi-inheritance solution complete. The interface solves some problems, while the internal class effectively implements "Multi-inheritance ". In general, the internal class should not be too long, otherwise it will appear very heavy.

Note the following when using anonymous internal classes:

A) The anonymous internal class cannot have Constructor

B) Anonymous internal classes cannot define any static members, methods, and classes.

C) The anonymous internal class cannot be public, protected, private, or static.

D) only one instance of the anonymous internal class can be created.

E) an anonymous internal class must be behind the new class. It is used to implicitly implement an interface or implement a class.

F) because the anonymous internal class is a local internal class, all restrictions on the local internal class take effect.

Nested class:

A common internal class holds a reference of a peripheral class, so it can be associated with an external class. When we need a nested class, we need to use the static keyword, in this way, the internal class is disconnected from the external class, and the non-static external class cannot be accessed from the internal class object.

public class InnerClass {static class A{static int a = 10;static void a(){System.out.println("this is A.a()!");}}}

Class inside the interface:

public interface Interface_Class {void say();class IC implements Interface_Class{@Overridepublic void say() {System.out.println("hello");}public static void main(String[] args) {new IC().say();}}}

It is suitable for creating public code for all classes that implement this interface.

Internal class inheritance, as we said, internal classes hold external class references. Therefore, during inheritance, We need to initialize this hidden reference. Please refer to the following code:

class AAA {class BBB {}}public class InnerClass_Extends extends AAA.BBB {public InnerClass_Extends(AAA aaa) {aaa.super();}public static void main(String[] args) {AAA aaa = new AAA();InnerClass_Extends ice = new InnerClass_Extends(aaa);}}

Finally, Let's sum up the reason for using internal classes: Each internal class can independently inherit the implementation of an interface and has no relationship with the external class (whether or not the external class implements this interface ).

To put it simply, the internal class is a perfect complement to the Java multi-Inheritance Mechanism. Why? As we have said, the implementation of multi-inheritance relies on interfaces. From the class perspective, there is no more inheritance. However, it is obviously impossible to use abstract classes to implement multi-inheritance. Therefore, internal classes must be used here. For example:

class AA{}abstract class BB{}class CC extends AA{BB makeB(){return new BB(){};}}public class Multi_Extends {static void takesA(AA a){}static void takesB(BB b){}public static void main(String[] args) {CC c = new CC();takesA(c);takesB(c.makeB());}}

In this way, the internal class is inherited.

This chapter is coming to an end. You are welcome to make some suggestions on the omission and negligence of the article! In the next chapter, I will introduce the Inheritance Mechanism of the following classes. You are welcome to continue reading and learning!


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.