Getting Started with Java Tutorial ten (abstract class interface anonymous inner class category)

Abstract class (abstract)

A class only defines a general form of all subclasses shared, as the details will be given to each sub-class to implement, this class has no specific example, only a number of abstract ideas, then this class is called an abstract class .

In the field of object-oriented, is mainly used for abstract class type hide. For example, if we develop a graphics editing software, you will find that there are areas of circular, triangular this specific concept, they are different, but they all belong to the shape of such a concept, the concept of shape in the area of ​​problem does not exist it is an abstract concept. It is because the concept of abstract no specific problem in the field corresponding to, for the abstract class so that it is not capable of abstraction characterized instantiated.

abstract class class_name
{
    abstract type method_name(parameter);
}

or represents the abstract class is abstract; class_name represents the name of an abstract class; method_name name represents the abstract method, if used to modify a prior abstract method, then the method is an abstract method, there can be a method body; Parameter representation parameter list.

The abstract keyword can only be used ordinary methods, static methods can not be used or constructor. Must contain at least one abstract class abstract method, and can not have all the abstract methods specific implementation, but should implement all abstract methods (Method body have) in their subclass, the method comprising one or more abstract classes you must add the abstract keyword before the declaration of its class to be declared as an abstract class. Because an abstract class does not define a complete implementation, so there is no abstract class own objects. Therefore, the use of any new attempt to create an abstract class object will result in a compile-time error.

public abstract class Shape
{
    public int width;     //几何图形的长
    public int height;    //几何图形的宽
    public Shape(int width,int height)
    {
        this.width=width;
        this.height=height;
    }
    public abstract double area();    //定义抽象方法,计算面积
}
public class Square extends Shape
{
    public Square(int width,int height)
    {
        super(width,height);
    }
    @Override
    public double area()//重写父类中的抽象方法,实现计算正方形面积的功能
    {
        return width*height;
    }
}
public static void main(String[] args)
{
    Square square=new Square(5,4);
    System.out.println("面积为:"+square.area());//输出:面积为:20
}

interface

An interface similar to a class, but the interface is not a member of the Executive body, it's just a combination of methods, properties, events, and indexers only. Interfaces can not be instantiated, the interface configuration is no method, no field. In the application, the interface is a specification that a package can be a common part of a plurality of class inheritance.

Different interface inheritance and implementation inheritance rules, a class has only one direct parent class, but can implement multiple interfaces. Java interface does not have any implementation described only public behavior, so Java interface Java abstract class more than the abstract. Java interface method can only be abstract and open, Java interfaces can not have constructors, Java interfaces can have public, Static and final properties.

Interface features and methods to implement the method separates, this separation is reflected in the interface often represents a role that packaging associated with the role of operations and properties, and to achieve this interface is the actor to play this role. A role to play by different actors, and between different actors in addition to playing a role beyond the common, does not require other in common.

For which the interface declaration of variables and methods have done many limitations, such as limitations of the interface features are summarized as follows:
an interface identifier of the public access control, allowing the use of any type; not specified public interface, which limited access to the packet belongs .
The method does not require additional statement modifiers, methods declared in the interface, implicitly declared as public domain (public) and abstract (abstract).
Variables declared in the Java interface are in fact constants, variables declared in the interface, implicitly declared as public, static and final, that is constant, so the variables defined in the interface must be initialized. Interface no construction method can not be instantiated.

definition

public interface interfaceName{
}
//例如
public interface Personlnterface{    
    String name;    //不合法,变量name必须初始化
    int age=20;     //合法,等同于 public static final int age=20;
    void getInfo(); //方法声明,等同于 public abstract void getInfo();
}

achieve

In the implementation class, all methods declared using the public access modifier. Whenever a realization by the method defined by the interface, it must be implemented as public, since all members of the interfaces are explicitly declared as public

public class Person implements Personlnterface
{
    public void getInfo(){
        return "Hello World";
    }
}

use

public static void main(String[] args){
    Personlnterface person = new Person();
    person.getInfo();//返回 HelloWorld
}

The difference between abstract classes and interfaces

In object-oriented design, all objects are depicted by class, but conversely, not all classes are used to describe the object, if a class does not describe a specific object, such class is an abstract class, abstract class, but the same abstract concept of the specific nature of that look different, precisely because abstract concepts do not correspond to the specific problem domain concepts, so the abstract class that can not be instantiated

Different syntaxes

The interface can be defined function, and may comprise abstract class implementation-defined functions and features. In the interface, all properties must be public, static, and final, all methods are abstract, it may default to not write the identifier described above; in an abstract class, comprising both abstract definition, can also contain specific method

public interface Animal
{
    public void eat();
    public String fly();
}
public abstract class Animal
{
    public abstract void eat();
    public String fly(){
        return "我会飞";
    };
}

Using the interface implementation class implements keyword; implementation class in the abstract class, use the extends keyword. Class that implements an interface can implement multiple interfaces, and a class of the abstract class can implement an abstract class.

//接口
public class concreteAnimal implements Animal
{
    public void eat(){}
    public void fly(){}
}
//抽象类
public class concreteAnimal extends Animal
{
    public void eat(){}
    public void fly(){}
}

Different design ideas

As can be seen from the implementation of the concrete implementation class in front of an abstract class, in fact, in Java, between abstract and concrete implementation class that is an inheritance, which means that if preclude the use of abstract class way, the parent and child class in concept should be the same. The interface is not the same, if by way of the interface, the parent class and subclass is not required on the same concept. Interface taking only common feature not related to each other between classes, rather than the relationship between the class concerned, it can not make the class hierarchy has the same behavior. Thus, we can say: An abstract class is an abstract object of a relationship a set of logically has the same properties and methods, and the interface is a set of logically to have the same properties and methods unrelated things a kind of abstraction.

The column used is a strong abstract class, has a use interface. Such as: a bird is an animal. Birds have a functional fly. Cat is an animal, but cats can not fly.

//接口
public interface Fly
{
    public void flyUp();
}
//抽象类
public abstract class Animal
{
    public abstract void eat();
}
//猫是一种动物
public class Cat extends Animal{
}
//鸟是一种动物,同时会飞
public class Bird extends Animal implements Run {
}

An abstract class is an abstract of things related to a set of logically has the same properties and methods, and the interface is an abstraction of something not related to a set of logically has the same properties and methods of the abstract class so represents the "is a" relationship, interface represents a "has a" relationship.

Inner classes

In an internal class category, which we call the internal class. Inner classes can realize the hidden, general non-inner classes is not allowed to have private and protected rights, but the inner class. Access to all the elements of inner classes have enclosing class.

Inner class can be divided into: internal instance of the class, static inner classes and members of inner classes, each class has its specific inside some of the features in this section and inner classes start with some relevant knowledge in detail.

Features inner classes are as follows:
inner class is still a separate class, inner classes after compilation will be compiled into a separate .class file, but preceded by the outer class class name and $ symbol.
Inner class can not access the ordinary way. Inner class is a member of the outer class, so the internal class member variables can be freely accessed outside the class, regardless of whether it is private.
Inner class declared as static, it can not easily access the member variables of the outer class, still you can only access static member variables outside the class.

public class Test
{
    public class InnerClass
    {
        public int getSum(int x,int y)
        {
            return x+y;
        }
    }
    public static void main(String[] args)
    {
        Test.InnerClass testInner =new Test().new InnerClass();
        int i = testInner.getSum(2/3);
        System.out.println(i); //输出5
    }
}

Examples of internal class

Examples of internal class that are not modified with internal static class

public class Outer
{
    class Inner
    {
        //实例内部类
    }
}

Outside static method of the outer class and other classes outside of the class, you must create an instance of the class by internal instance of the outer class, if there are nested, the inner class can access all members of the outer class

public class Outer
{
    class Inner{}
    Inner i=new Inner();    //类内部不需要创建外部类实例
    public void method0()
    {
        Inner j=new Inner();    //类内部不需要创建外部类实例
    }
    public static void method1()
    {
        Inner r=new Outer().new inner();    //静态方法需要创建外部类实例
    }
    class Inner1
    {
        Inner k=new Inner();    //不需要创建外部类实例
    }
}
class OtherClass
{
    Outer.Inner i=new Outer().new Inner();    //其他类使用时需要创建外部类实例
}

Static inner classes

Static inner class refers to the use of static inner classes modified

public class Outer
{
    static class Inner
    {
        //静态内部类
    }
}

When creating an instance of a static inner classes you do not need to create an instance of the outer class

public class Outer
{
    static class Inner{}
}
class OtherClass
{
    Outer.Inner oi=new Outer.Inner();
}

Partial inner class

It refers to the internal local inner classes in a class defined in the method

public class Test
{
    public void method()
    {
        class Inner
        {
            //局部内部类
        }
    }
}

Partial internal classes and local variables can not be used to control access modifier (public, private and protected) and the static modifier modifications, partial internal category is only valid in the current method, the partial inner class can access all members of the class of external

public class Test
{
    Inner i=new Inner();    //编译出错
    Test.Inner ti=new Test.Inner();    //编译出错
    Test.Inner ti2=new Test().new Inner();    //编译出错
    public void method()
    {
        class Inner{}
        Inner i=new Inner();
    }
}

Anonymous class

Anonymous inner class category refers to no class name must be used to declare the class when creating a new statement

new<类或接口>()
{
    //类的主体
};

This form of the new statement to declare a new anonymous class, it's a given class is extended, or implement a given interface. The use of anonymous classes make the code more concise, compact, modular higher degree of
anonymous class implemented in two ways:
to inherit a class, override its methods.
Implementing an interface (may be a plurality), which implement methods.

public class Out
{
    void show()
    {
        System.out.println("调用 Out 类的 show() 方法");
    }
}
public class TestAnonymousInterClass
{
    //在这个方法中构造一个匿名内部类
    private void show()
    {
        Out anonyInter=new Out()
        {
            //获取匿名内部类的实例
            void show()
            {
                System.out.println("调用匿名类中的 show() 方法");
            }
        };
        anonyInter.show();
    }
    public static void main(String[] args)
    {
        TestAnonymousInterClass test=new TestAnonymousInterClass();
        test.show();
    }
}

Guess you like

Origin www.cnblogs.com/lilinfeng/p/10995743.html