Java 面向对象概念

 

Interface 接口

An interface defines a protocol of communication between two objects.

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.

A class that implements an interface must implement all the methods declared in the interface. 接口中的方法都是implicitly abstract。

An interface name can be used anywhere a type can be used.

Polymorphism 多态

 不同的子类overridden 父类的同一方法,每个子类具有单独的实现。

Instance Methods(实例方法)vs Class Methods (类方法)

public class Animal {



    public static void testClassMethod(){

        System.out.println("The class method" + " in Animal");

    }

    

    public void testInstanceMethod(){

        System.out.println("The instance method"+" in Animal ");

    }

}
public class Cat extends Animal {



    /*

     *The overriding method has the same name, number and type of parameters, and return type as the method it overrides

    */

    

    //Class Method类方法,需要通过类名来调用,子类hidden父类的方法

    public static void testClassMethod(){

        System.out.println("The class Method in Cat");

    }

    

    //Instance Method实例方法,通过类的实例来调用,子类overridden父类的方法。

    public void testInstanceMethod(){

        System.out.println("The instance Method in Cat");

    }



    public static void main(String[] args) {



        Cat myCat = new Cat();

        Animal myAnimal = myCat;

        myAnimal.testInstanceMethod(); // 总是调用覆盖过的子类方法

        super.testInstanceMethod(); //可以通过super来调用父类被覆盖的方法。
     Animal.testClassMethod(); // 取决于是子类调用,还是父类调用 } }

 super

super 可用来调用父类被覆盖的方法。

super 可用来调用父类构造器constructor。

默认自动调用父类无参构造器,可以显示调用含参数的构造器。

Final

final 可用来声明方法不可被覆盖,类不可被继承。

final static用于定义不变的变量。

Abstract Methods and Classes

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon),like

//含有抽象方法的类必须为抽象

public abstract class GraphicObject {

   // declare fields

   // declare non-abstract methods

   abstract void draw();

}

子类必须实现了父类的所有抽象方法,否则子类必须也为抽象,留给它的子类去实现剩余的抽象方法。

Abstract Classes vs Interfaces

abstract classes can contain fields that are not static and final, and they can contain implemented methods.

If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way.

abstract class can implements an interface, 提供部分的方法实现。

抽象方法不能被实例化。

你可能感兴趣的:(java)