java===java basic learning (15)---abstract, interface

 

abstract

// This is an abstract class 
abstract  class Animal
{
    String name;
    int age;
    abstract public void cry();
        
    }

// When the parent class inherited by a class is abstract
 // We need to implement all the methods in the inherited class 
class cat extends Animal
{
    public void cry() {
        // do nothing
        
    }
}

 

When a class is decorated with the abstract keyword, the class is an abstract class.
When a method is decorated with the abstract keyword, the method is an abstract method.

Note:
Abstract classes cannot be instantiated.
Abstract classes do not necessarily contain abstract methods. That is, an abstract class can have no abstract method.
Once the class contains abstract methods, the class must be declared abstract
abstract methods cannot have subjects, for example:

 

interface

/*
 * Function: interface
 *
 */

package demo;

public class test3 {
    public static void main(String []args) {
        Computer computer = new Computer();
        
        Camera camera1 = new Camera();
        
        Phone phone1 = new Phone();
        
        computer.useUsb(camera1);
        computer.useUsb(phone1);
        
    }
}

interface Usb
{
    int a = 1 ;
     // declare two methods
     // start work 
    public  void start();
     // stop work 
    public  void stop();
    
}


// Write a camera class and implement the usb interface
 // An important principle: when a class implements an interface
 // The class is required to implement all the methods of this interface 
class Camera implements Usb
{
    public void start()
    {
        System.out.println( "I'm the camera, start working!" );
    }
    
    public void stop()
    {
        System.out.println( "I am the camera, stop working!" );
        
    }
}

// Implement a mobile phone class 
class Phone implements Usb
{
    public void start()
    {
        System.out.println( "I'm a phone, start working!" );
    }
    
    public void stop()
    {
        System.out.println( "I'm a phone, stop working!" );
    }
    
}


class Computer
{
    public void useUsb(Usb usb) 
    {
        usb.start();
        usb.stop();
    }
}


接口注意事项:

1.接口不能被实例化
2.接口中的所有方法都不能有主体
3.一个类可以实现多个接口
4.接口中可有变量[但,变量不能用 private 和 protected 修饰]
a.接口中的变量,本质上都是static的,不管你加不加static修饰
b.在Java开发中,我们经常把常用的变量,定义在接口中,作为全局变量使用
5.一个接口不能继承其它的类,但是可以继承别的接口


小结:
接口随是更加抽象的抽象的类,抽象类里的方法可以有方法体,接口里的所有方法都没有方法体。接口体现了程序设计的多态和高内聚低耦合的设计思想。

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324523010&siteId=291194637