码迷,mamicode.com
首页 > 编程语言 > 详细

Java笔记:包与接口

时间:2018-02-12 18:40:52      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:val   静态   turn   存在   out   str   多个   range   string   

一、包

使用package关键字声明包。包的作用相当于命名空间。若没有显式地声明类所属的包,那么类将会被放到默认的包中,默认的包没有名称。包支持层次化地创建,即支持嵌套。

使用import关键字导入包。支持导入包中的类或包,若不导入声明变量则需要写上完整的路径。

import java.lang.*;//导入包
import java.util.ArrayList;//导入类

class Solution {
    ArrayList arrayList;//已导入
    java.util.LinkedList linkedList;//未导入
}

 

二、接口

声明接口。接口的普通方法不能存在具体实现。

interface Color {
    void setColor(int color);
    int getColor();
}

interface Line {
    void setLength(int length);
    int getLength();
}

 

实现接口。类可以同时实现多个接口。

class ColorfulLine implements Color, Line {
    int color;
    int length;

    ColorfulLine(int color, int length) {
        this.color = color;
        this.length = length;
    }

    @Override
    public void setColor(int color) {
        this.color = color;
    }

    @Override
    public int getColor() {
        return color;
    }

    @Override
    public void setLength(int length) {
        this.length = length;
    }

    @Override
    public int getLength() {
        return length;
    }
}

 

嵌套接口。接口为类或其他接口的成员时,有更多的访问限制选择。

class A {
    public interface i {
        boolean isNegative(int x);
    }
}

class B implements A.i {
    @Override
    public boolean isNegative(int x) {
        return x < 0;
    }
}

 

接口变量。可使用接口将共享的常量导入多个类种。

interface RBG {
    int RED = 0;
    int BLUE = 1;
    int GREEN = 2;
}

 

扩展接口。接口可以继承其他接口。

interface Color extends RBG {
    int ORANGE = 3;
    int YELLOW = 4;
    int CYAN = 5;
    int PURPLE = 6;
}

 

默认实现。接口可声明默认方法并可重写。

interface i {
    default void show() {
        System.out.println("Hi");
    }
}

class A implements i {
    @Override
    public void show() {
        System.out.println("Hello");
    }
}

 

变量成员与静态方法可直接被调用。

interface i {
    int val = 0;

    static void show() {
        System.out.println(val);
    }
}

class Solution {
    public static void main(String[] args) {
        i.show();
        System.out.println(i.val);
    }
}

 

Java笔记:包与接口

标签:val   静态   turn   存在   out   str   多个   range   string   

原文地址:https://www.cnblogs.com/arseneyao/p/8444798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!