1.final关键字
修饰类:类不能被继承
修饰方法:方法不能被重写
修饰变量:变量仅能被赋值一次;基本数据类型的值不能改变,引用数据类型的地址不能改变
// 以下做法无误 final int[] a = {1, 2, 3}; a[1] = 666;2.单例类
一个类只能创建一个对象
package com.popo.danli; public class A { // 单例设计模式 // 2.创建唯一对象,并且私有化,不能在外部修改 private static A a = new A(); // 1.私有化构造方法 private A() {} // 3.提供一个公共的静态方法 public static A getInstance() { return a; } }package com.popo.danli; public class DanLi { public static void main(String[] args) { A a1 = A.getInstance(); A a2 = A.getInstance(); System.out.println(a1 == a2); //True // 错误的写法 // A.getInstance() = null; } }3.枚举类
用于信息的分类和标志
package com.popo.meiju; public enum A { // 枚举常量 X, Y, Z; }package com.popo.meiju; public class EnumDemo { public static void main(String[] args) { A x = A.X; A y = A.Y; A z = A.Z; System.out.println(x); // 输出: X System.out.println(y); // 输出: Y System.out.println(z); // 输出: Z System.out.println(A.X.name()); // 输出: X System.out.println(A.Y.name()); // 输出: Y System.out.println(A.Z.name()); // 输出: Z System.out.println(A.X.ordinal()); // 输出: 0 System.out.println(A.Y.ordinal()); // 输出: 1 System.out.println(A.Z.ordinal()); // 输出: 2 xyz(A.X); } // 只能传入A枚举类的常量 public static void xyz(A a){ switch (a) { case X: System.out.println("X"); break; case Y: System.out.println("Y"); break; case Z: System.out.println("Z"); break; } } }4.抽象类
抽象类和抽象方法由abstract关键字修饰
抽象类中可以没有抽象方法
有抽象方法的类必须是抽象类
抽象方法没有方法体
抽象类不能创建对象
抽象类作为父类时,其子类必须实现所有抽象方法
使用抽象类可以更好地支持多态
可以将重复的代码写入模板方法,在模板方法中调用子类实现的抽象方法
package com.popo.chouxiang; public abstract class Animal { // 模板方法 public void start_day() { System.out.println("This animal gets up"); eat(); System.out.println("This animal sleeps"); } public abstract void eat(); }package com.popo.chouxiang; public class Cat extends Animal { public void eat() { System.out.println("This cat is eating fish"); } }package com.popo.chouxiang; public class Dog extends Animal{ @Override public void eat() { System.out.println("This dog is eating bone"); } }package com.popo.chouxiang; public class AbstractDemo { public static void main(String[] args) { Animal animal1 = new Dog(); animal1.start_day(); // This animal gets up, This dog is eating bone, This animal sleeps Animal animal2 = new Cat(); animal2.start_day(); // This animal gets up, This cat is eating fish, This animal sleeps } }5.接口
接口中的成员变量都是常量,成员方法都是抽象方法
接口不能创建对象,只能被实现
一个类只能继承一个类,但可以实现多个接口,并且要实现所有接口的抽象方法
一个接口可以继承多个接口
当多个接口中存在同名但结构不同(如有无返回值)的方法,则不能多继承和多实现
如果父类和接口中有同名方法,优先调用父类方法
package com.popo.jiekou; public class InterfaceDemo { public static void main(String[] args) { A a = new B(); a.run(); // B is running } } interface A { // public static final String NAME = "AAA"; String NAME = "AAA"; // public abstract void run(); void run(); } class B implements A { public void run() { System.out.println("B is running"); } }