class Cat { public void eat() { System.out.println("猫吃鱼"); } } class CatOperator { public void useCat(Cat c) { //Cat c = new Cat(); c.eat(); } public Cat getCat() { Cat c = new Cat(); return c; } } public class CatDemo { public static void main(String[] args) { //创建操作类对象,并调用方法 CatOperator co = new CatOperator(); Cat c = new Cat(); co.useCat(c); Cat c2 = co.getCat(); //new Cat() c2.eat(); } }
abstract class Animal { public abstract void eat(); } class Cat extends Animal { @Override public void eat() { System.out.println("猫吃鱼"); } } class AnimalOperator { public void useAnimal(Animal a) { //Animal a = new Cat(); a.eat(); } public Animal getAnimal() { Animal a = new Cat(); return a; } } public class AnimalDemo { public static void main(String[] args) { //创建操作类对象,并调用方法 AnimalOperator ao = new AnimalOperator(); Animal a = new Cat(); ao.useAnimal(a); Animal a2 = ao.getAnimal(); //new Cat() a2.eat(); } }
interface Jumpping { void jump(); } class JumppingOperator { public void useJumpping(Jumpping j) { //Jumpping j = new Cat(); j.jump(); } public Jumpping getJumpping() { Jumpping j = new Cat(); return j; } } class Cat implements Jumpping { @Override public void jump() { System.out.println("猫可以跳高了"); } } public class JumppingDemo { public static void main(String[] args) { //创建操作类对象,并调用方法 JumppingOperator jo = new JumppingOperator(); Jumpping j = new Cat(); jo.useJumpping(j); Jumpping j2 = jo.getJumpping(); //new Cat() j2.jump(); } }
/* 格式: class 外部类名{ 修饰符 class 内部类名{ } } */ class Outer { public class Inner { } }
/* 内部类访问特点: 内部类可以直接访问外部类的成员,包括私有 外部类要访问内部类的成员,必须创建对象 */ public class Outer { private int num = 10; public class Inner { public void show() { System.out.println(num); } } public void method() { Inner i = new Inner(); i.show(); } }
成员内部类的定义位置
外界创建成员内部类格式
成员内部类的推荐使用方案
class Outer { private int num = 10; private class Inner { public void show() { System.out.println(num); } } public void method() { Inner i = new Inner(); i.show(); } } public class InnerDemo { public static void main(String[] args) { //Outer.Inner oi = new Outer().new Inner(); //oi.show(); Outer o = new Outer(); o.method(); } }