内部类(调用某些框架会用到,使用场景较少)
public class Outer {
public class InnerTool { // 内部类
public int add(int a,int b){
return a+b;
}
}
}
创建在一个类的类部,Outer称为外部类,InnerTool 称为内部类。
内部类实例化
调用内部类,实例化要在Outer内完成
public class OuterUtil {
public class InnerTool { // 内部类
public int add(int a,int b){
return a+b;
}
}
private InnerTool tool = new InnerTool();
}
public class OuterUtil {
public class InnerTool { // 内部类
public int add(int a,int b){
return a+b;
}
}
private InnerTool tool = new InnerTool();
public int add(int a,int b,int c){
return tool.add( tool.add(a,b) , c );
}
}
其他类访问实例内部类
必须先实例外部类,一般情况下,不建议在外面直接调用内部类
OuterUtil.InnerTool tool = new OuterUtil().new InnerTool();
静态内部类
public class OuterUtil {
public static class InnerTool { // 内部类
public int add(int a,int b){
return a+b;
}
}
}
直接调用不需要实例化外部类
import com.youkeda.util.OuterUtil;
// 静态内部类是需要单独 import 的
import com.youkeda.util.OuterUtil.InnerTool;
public class OuterUtilTest {
public static void main(String[] args){
InnerTool tool = new InnerTool();
int sum = tool.add(1,2);
System.out.println(sum);
}
}
布局内部类(很少见)
public class Tester {
public void test(){
class B{
int a;
}
B b = new B();
}
}
匿名类(日常使用较多,特别是多线程)
public class ATest {
public static void main(String[] args){
A a = new A(){
public void method(){
System.out.println("执行内部类");
}
};
a.method();
}
}
A a = new A(){ }语法,其实匿名类的效果如下面的类
public class AImpl implements A{
public void method(){
System.out.println("执行类");
}
}
除了实现接口还可以是继承父类
public class Sub {
public void print(){
}
}
public class SubTest {
public static void main(String[] args){
Sub sub = new Sub(){
public void print(){
System.out.println("执行内部类");
}
};
sub.print();
}
}
这个匿名类相当于
public class SubNode extends Sub {
public void print(){
System.out.println("执行");
}
}
抽象类(建议用接口代替抽象类)
抽象类首先是一个父类,然后他的实例化必须要是有子类就像接口必须通过实现类才能实例化一样
// 定义一个武器的抽象类
public abstract class Weapon{
// 抽象方法:攻击
public abstract void attack();
}
关键字 abstract
声明抽象类后,他的子类必须要实现抽象方法,
public class GoldenBar extends Weapon {
public void attack(){
System.out.println("使用金箍棒进行劈一棍");
}
}
接口的默认方法
public interface Vehicle {
default void print(){
System.out.println("我是一辆车!");
}
}
覆盖接口默认方法
public class Car implements Vehicle {
public void print(){
System.out.println("我是一辆汽车!");
}
}
不覆盖
public class Car implements Vehicle {
}