final 关键字在 Java 中被称为完结器, 表示最终的意思:
final 能声明类, 方法, 属性:
1, 使用 final 声明的类不能被继承;
2, 使用 final 声明的方法不能被重写;
3, 使用 final 声明的变量变成常量, 不可以被修改.(常规大写)
抽象类概念:
包含一个抽象方法的类就是抽象类;
抽象方法:
声明而未被实现的方法, 抽象方法必须使用 abstract 关键字声明
抽象类被子类继承, 子类 (如果不是抽象类) 必须重写抽象类中的所有抽象方法
定义格式:
abstract class className{
属性;
方法;
抽象方法;
}
抽象类不能直接实例化, 要通过其子类进行实例化.
- package com.jike.finalDemo;
- abstract class Abs{
- private int age;
- public void setAge(int age) {
- this.age = age;
- }
- public int getAge() {
- return age;
- }
- public void tell() {
- }
- public abstract void say();
- }
- class AbsDemo extends Abs{
- public void say() {
- System.out.println(getAge());
- }
- }
- public class abstractDemo {
- public static void main(String[] args) {
- AbsDemo absDemo=new AbsDemo();
- absDemo.setAge(50);
- absDemo.say();
- }
- }
输出:
50
接口是 Java 中最重要的概念, 接口可以理解为一种特殊的类, 里面全部是由全局常量和公共的抽象方法组成.
接口的格式:
interface interfaceName{
全局常量
抽象方法
}
接口的实现也必须通过子类, 使用关键字 implements, 而接口是可以多实现的;
一个子类可以同时继承抽象类和实现接口;
一个接口不能继承一个抽象类, 但是可以通过 extends 关键字同时继承多个接口, 实现接口的多继承.
- package com.jike.finalDemo;
- interface Inter{
- public static final int AGE=50; // 全局常量, 大写
- public abstract void tell(); // 抽象方法
- }
- interface Inter2{
- public abstract void say();
- }
- abstract class Abs1{
- public abstract void print();
- }
- class A extends Abs1 implements Inter,Inter2{ // 接口的实现也必须通过子类, 使用关键字 implements, 而接口是可以多实现的; 一个子类可以同时继承抽象类和实现接口;
- public void tell() {
- System.out.println("A 的 tell 方法");
- }
- public void say() {
- System.out.println("say something");
- }
- public void print() {
- System.out.println("print something");
- }
- }
- interface Inter3 extends Inter,Inter2{ // 接口可以继承多个接口, 类不能多继承
- }
- public class interfaceDemo {
- public static void main(String[] args) {
- // Inter i=new Inter(); // 接口不能直接实例化
- A a=new A();
- a.tell();
- System.out.println(Inter.AGE);
- a.say();
- a.print();
- }
- }
输出:
A 的 tell 方法
- 50
- say something
- print something
来源: http://www.bubuko.com/infodetail-2969667.html