public class Outer { private Inner inner=null; private double r; String b; public Inner getInnerInstance(){//用于返回一个内部类对象 if (inner==null) inner=new Inner(); return inner; } private class Inner{//成员内部类,用private修饰,只能外部类的内部访问 final static int t=1;//成员内部类不能定义静态成员,final修饰的除外 public void draw(){ System.out.println("绘制一个圆,半径为"+r); } } }
public class Test { public static void main(String[] args) { Outer.Inner inner=new Outer.Inner();//静态内部类可以被其他类直接访问和实例化,而不需要先实例化外部类。 inner.draw(); } } class Outer { int t=0; static String desc="123"; static class Inner{ static int x=10; { System.out.println("这里是静态内部类的代码块"); } public static void draw(){ System.out.println("t的值:");//这里会编译报错 System.out.println("desc的值:"+desc); } } }
public class Test { public static void main(String[] args) { Calculator calculator=new Calculator() {// 创建一个匿名内部类实现Calculator接口 @Override public int calculate(int a, int b) { return a + b; } }; System.out.println(calculator.calculate(2,3)); } } interface Calculator { int calculate(int a, int b); }
class Outer{ public void test(){ int x=20; class Inner{ //在方法内定义 public void print(){ System.out.println("我今年"+x); } } new Inner().print(); // 局部内部类必须在方法内部实例化,然后return出去或者直接调用其方法。 } public static void main(String[] args) { Outer outer = new Outer(); outer.test(); } }
class Father { public int eat(){ return 10; } } class Mother { public int fly(){ return 20; } } class Son { class Father_1 extends Father{ public int eat(){ return super.eat() + 10; } } class Mother_1 extends Mother{ public int fly(){ return super.fly() - 7; } } public int geteat(){ return new Father_1().eat(); } public int getfly(){ return new Mother_1().fly(); } } public class Test { public static void main(String[] args) { Son son = new Son(); System.out.println( son.geteat()); System.out.println( son.getfly()); } }