面向对象编程(高级)
类变量和类方法
01:
package ChildDemo;public class Child {private String name;public static int cnt = 0;public Child(String name){this.name = name;}public void join(){System.out.println(name +"join the game");}
}//=========================================package ChildDemo;public class TestDemo01 {public static void main(String[] args){Child ch1 = new Child("Tom");ch1.join();ch1.cnt++;Child ch2 = new Child("Bom");ch2.join();ch2.cnt++;Child ch3 = new Child("Jack");ch3.join();ch3.cnt++;System.out.println(Child.cnt);}
}
什么是类变量和如何定义
01:
package HomeWork07;public class VisitStatic {public static void main(String[] args){System.out.println(A.name);A a = new A();System.out.println("a.name = "+a.name);}}//hspedu
//a.name = hspeduclass A
{public static String name = "hspedu";}
注意事项和细节讨论
类方法基本介绍
01:
package HomeWork07;public class StaticMethod {public static void main(String[] args) {Stu tom = new Stu("tom");
// tom.payFee(100);//OKStu.payFee(100);Stu marry = new Stu("marry");marry.payFee(200);Stu.showFee();}
}class Stu{private String name;private static double fee = 0;public Stu(String name) {this.name = name;}public static void payFee(double fee){Stu.fee +=fee;}public static void showFee(){System.out.println("学费有 = "+Stu.fee);}}
类方法经典的使用场景
01:
System.out.println(Math.sqrt(9));//3
02:
class MyTools
{public static double calSum(double n1,double n2){return n1+n2;}
}
注意事项
- 静态方法只能访问静态成员
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TM4MzTp8-1634390172741)(C:\Users\Tom\AppData\Roaming\Typora\typora-user-images\image-20210917134451584.png)]
小练习
main方法语法
深入理解main方法
01:
package WorkDemo02323;public class Main01 {private static String name = "hspedu";private int n1 = 100000;public static void hi(){System.out.println("hi");}public void cry(){System.out.println("cry");}public static void main(String[] args){System.out.println("name = "+name);hi();//静态方法main不可以访问本类的非静态成员//System.out.println("n1 = "+n1);//Error//cry();//ErrorMain01 main01 = new Main01();System.out.println(main01.n1);main01.cry();}
}
案例演示
01:
package WorkDemo01;public class Main02 {public static void main(String[] args){for (int i = 0;i<args.length;i++){System.out.println(args[i]);}}
}
代码块
01:
package CodeBlockDemo;public class CodeBlock {public static void main(String[] args){Movie hello_lin = new Movie("hello lin");Movie hello_lin02 = new Movie("hello lin",2131,"DAFS");}
}class Movie
{private String name;private double price;private String director;{System.out.println("001");System.out.println("002");System.out.println("003");}public Movie(String name) {this.name = name;System.out.println("Movie(String name)");}public Movie(String name, double price) {this.name = name;this.price = price;}public Movie(String name, double price, String director) {this.name = name;this.price = price;this.director = director;System.out.println("Movie (String name,double price,String director)");}
}
结果如下:
注意事项和细节讨论
01:
public class CodeBlockDemo01 {public static void main(String[] args){//1 situationAA aa = new AA();//static code block}
}//class BB
//{
// static {
// System.out.println("BB static codeblock");
// }
//}class AA extends BB
{static {System.out.println("static code block");}}
02:
public class CodeBlockDemo01 {public static void main(String[] args){//2 situationAA aa = new AA();// BB static codeblock
// static code block}
}class BB
{static {System.out.println("BB static codeblock");}
}class AA extends BB
{static {System.out.println("static code block");}}
03:
public class CodeBlockDemo01 {public static void main(String[] args){//3 situationAA aa = new AA();System.out.println(Cat.n1);// BB static codeblock
// static code block
// Cat static codeblock
// 999}
}class Cat
{public static int n1 = 999;static {System.out.println("Cat static codeblock");}
}class BB
{static {System.out.println("BB static codeblock");}
}class AA extends BB
{static {System.out.println("static code block");}}
- static代码块,是在类加载时执行的,而且只会执行一次
01:
public class CodeBlockDemo01 {public static void main(String[] args){AA aa = new AA();System.out.println(Cat.n1);System.out.println(Cat.n1);// BB static codeblock
// static code block
// Cat static codeblock
// 999
// 999}
}class Cat
{public static int n1 = 999;static {System.out.println("Cat static codeblock");}
}class BB
{static {System.out.println("BB static codeblock");}
}class AA extends BB
{static {System.out.println("static code block");}}//================================================public class CodeBlockDemo01 {public static void main(String[] args){DD dd = new DD();DD dd1 = new DD();//DD RUSH!!!}
}class DD
{static {System.out.println("DD RUSH!!!");}
}
-
普通的代码块,在创建对象实例时,会被隐式的调用,每创建一次,就会调用一次,如果只是使用类的静态成员,普通代码块并不会执行
-
普通代码块,在new对象时被调用,而且是每创建一个对象就调用一次,可以简单的理解为,普通代码块是构造器的补充
01:
public class CodeBlockDemo01 {public static void main(String[] args){System.out.println(DD.n1);// DD RUSH!!!
// 8888}
}class DD
{public static int n1 = 8888;static {System.out.println("DD RUSH!!!");}{System.out.println("DD code");}
}class Cat
{public static int n1 = 999;static {System.out.println("Cat static codeblock");}
}class BB
{static {System.out.println("BB static codeblock");}
}class AA extends BB
{static {System.out.println("static code block");}}
01:
package CodeBLockDemo02;public class CodeBlockDetail02 {public static void main(String[] args){A a = new A();
// getN1
// A static 01}
}class A
{private static int n1 = getN1();static {System.out.println("A static 01");}public static int getN1(){System.out.println("getN1");return 100;}
}//============================================package CodeBLockDemo02;public class CodeBlockDetail02 {public static void main(String[] args){A a = new A();// A static 01
// getN1}
}class A
{static {System.out.println("A static 01");}private static int n1 = getN1();public static int getN1(){System.out.println("getN1");return 100;}
}
02:
package CodeBLockDemo02;public class CodeBlockDetail02 {public static void main(String[] args){A a = new A();// A static 01
// getN1
// getN2
// normal codeblock}
}class A
{private int n2 = getN2();{System.out.println("normal codeblock");}static {System.out.println("A static 01");}private static int n1 = getN1();public static int getN1(){System.out.println("getN1");return 100;}public int getN2(){System.out.println("getN2 ");return 200;}
}//=================================================package CodeBLockDemo02;public class CodeBlockDetail02 {public static void main(String[] args){A a = new A();// A static 01
// getN1
// normal codeblock
// getN2}
}class A
{{System.out.println("normal codeblock");}private int n2 = getN2();static {System.out.println("A static 01");}private static int n1 = getN1();public static int getN1(){System.out.println("getN1");return 100;}public int getN2(){System.out.println("getN2 ");return 200;}}
03:
package CodeBLockDemo02;public class CodeBlockDetail02 {public static void main(String[] args){A a = new A();// A static 01
// getN1
// normal codeblock
// getN2
// A constructor}
}class A
{{System.out.println("normal codeblock");}private int n2 = getN2();static {System.out.println("A static 01");}private static int n1 = getN1();public static int getN1(){System.out.println("getN1");return 100;}public int getN2(){System.out.println("getN2 ");return 200;}public A(){System.out.println("A constructor");}}
01:
package CodeBLockDemo02;public class CodeBlockDetail03 {public static void main(String[] args){new BBB();// AAA codeBlock
// AAA() 构造器被调用...
// BBB的normal codeBlock
// BB() 构造器被调用...}
}class AAA
{{System.out.println("AAA codeBlock");}public AAA(){System.out.println("AAA() 构造器被调用...");}
}class BBB extends AAA{{System.out.println("BBB的normal codeBlock");}public BBB(){System.out.println("BB() 构造器被调用...");}}
01:
package CodeBlockDemo003;public class TestWork {public static void main(String[] args){new B02();// getVal01
// A02的一个静态代码块...
// getVal03
// B02的一个静态代码块
// A02的第一个普通代码块...
// getVal02
// A02的构造器
// getVal04
// B02的第一个普通代码块...
// B02的构造器}
}class A02
{private static int n1 = getVal01();static{System.out.println("A02的一个静态代码块...");}{System.out.println("A02的第一个普通代码块...");}public int n3 = getVal02();public static int getVal01(){System.out.println("getVal01");return 10;}public int getVal02(){System.out.println("getVal02");return 10;}public A02(){System.out.println("A02的构造器");}
}class B02 extends A02{private static int n3 = getVal03();static {System.out.println("B02的一个静态代码块");}public int n5 = getVal04();{System.out.println("B02的第一个普通代码块...");}public static int getVal03(){System.out.println("getVal03");return 10;}public int getVal04(){System.out.println("getVal04");return 10;}public B02(){System.out.println("B02的构造器");}
}
02:
package CodeBlockDemo003;public class TestDemo0123 {public static void main(String[] args){new C02();
// 200
// 100
// 200}
}class C02
{private int n1 =100;private static int n2 = 200;private void m1(){}private static void m2(){}static {//System.out.println(n1);//ErrorSystem.out.println(n2);//ok//m1();//Errorm2();}{System.out.println(n1);System.out.println(n2);//okm1();m2();}}
小练习
01:
package CodeBlockDemo003;public class Person {public static int total;static{total = 100;System.out.println("in static block");}}class Test
{public static void main(String[] args){System.out.println("total = "+Person.total);System.out.println("total = "+Person.total);// in static block
//total = 100
//total = 100}
}
02:
单例设计模式
单利模式-饿汉式
-
1.将构造器私有化
-
2.在类的内部直接创建对象(该对象是static)
-
3.提供一个public的static方法,return 该对象
-
对象,通常是重量级的对象,饿汉式可能造成创建了对象,但是没有使用
01:
package SingleDemo;public class SingleTon01 {public static void main(String[] args){GirlFriend instance = GirlFriend.getInstance();System.out.println(instance);GirlFriend instance02 = GirlFriend.getInstance();System.out.println(instance02);// GirlFriend{name='xiaoRed'}
// GirlFriend{name='xiaoRed'}}}class GirlFriend
{private String name;private static GirlFriend gf = new GirlFriend("xiaoRed");private GirlFriend(String name) {this.name = name;}public static GirlFriend getInstance(){return gf;}@Overridepublic String toString() {return "GirlFriend{" +"name='" + name + '\'' +'}';}
}
单例模式-懒汉式
- 构造器私有化
- 定义一个static静态属性对象
- 提供一个public的static方法,可以return一个Cat对象
- 懒汉式,只有当用户使用getInstance时,才return Cat对象,后面再次调用时,会返回上次创建的Cat对象,从而保证了单例
01:
package SingleDemo;public class SingleTon02 {public static void main(String[] args){Cat ins = Cat.getInstance();System.out.println(ins);Cat ins2 = Cat.getInstance();System.out.println(ins2);}// Cat constructor
// Cat{name='XiaoCute'}
// Cat{name='XiaoCute'}}class Cat
{private String name;private static Cat cat;private Cat(String name) {System.out.println("Cat constructor");this.name = name;}public static Cat getInstance(){if (cat==null){cat = new Cat("XiaoCute");}return cat;}@Overridepublic String toString() {return "Cat{" +"name='" + name + '\'' +'}';}
}
tip:
- 当多个进程同时进入时,有可能会导致创建多个Cat对象(保留最后那个对象),从而破坏单例
public static Cat getInstance(){if (cat==null){cat = new Cat("XiaoCute");}return cat;}
饿汉式VS懒汉式
小结
final关键字
01:
final class C{}
02:
class C{public final void hi(){}
}
03:
class E{public final double TAX_RATE = 0.08;
}
04:
class F{public void cry(){//这时,NUM 也称为 局部变量final double NUM = 0.01;}
}
final使用注意事项和细节讨论
01:
package DemoFinal;public class FinalDetail01 {public static void main(String[] args){}
}class AA
{public final double TAX_RATE = 0.08;//public final double TAX_RATE01;//Errorpublic final double TAX_RATE02;public final double TAX_RATE03;public AA(){TAX_RATE02 = 0.09;}{TAX_RATE03 = 0.07;}
}
02:
public class FinalDetail01 {public static void main(String[] args){}
}class BB
{public static final double TAX_RATE = 99.9;public static final double TAX_RATE01;//Error static final 不能在构造器赋值
// public static final double TAX_RATE03;
//
// public BB()
// {
// TAX_RATE03 = 0.9;
// }static {TAX_RATE01 = 0.88;}
}
03:
public class FinalDetail01 {public static void main(String[] args){CC c = new CC();}
}final class CC{}
04:
public class FinalDetail01 {public static void main(String[] args){new EE().cal();}
}class DD{public final void cal(){System.out.println("cal()方法");}
}class EE extends DD{}
01:
public class FinalDetail02 {public static void main(String[] args){}
}final class AAA
{//一般来说,如果一个类已经是final类,就没有必要再将方法修饰成final方法public final void cry(){System.out.println("cry()");}
}
02:
public class FinalDetail02 {public static void main(String[] args){System.out.println(BBB.num);}//10000
}class BBB
{public final static int num = 10000;static {System.out.println("codeBlock ing");}
}//================================================public class FinalDetail02 {public static void main(String[] args){System.out.println(BBB.num);}//10000
}class BBB
{public static final int num = 10000;static {System.out.println("codeBlock ing");}
}//=================================================public class FinalDetail02 {public static void main(String[] args){System.out.println(BBB.num);}
// codeBlock ing
//10000
}class BBB
{public static int num = 10000;static {System.out.println("codeBlock ing");}
}
final应用实例
01:
public class FinalExercise01 {public static void main(String[] args){Circle circle = new Circle(5.0);System.out.println("area = "+circle.calArea());//area = 78.5}
}class Circle
{private double radius;private final double PI;// = 3.14;public Circle(double radius) {this.radius = radius;//PI = 3.14;}{PI = 3.14;}public double calArea(){return PI*radius*radius;}}
02:
抽象类
01:
package AbstractDemo01;public class Abstract01 {public static void main(String[] args){}
}abstract class Animal
{private String name;public Animal(String name){this.name = name;}public abstract void eat();//public abstract void eat(){};//ERROR
}
抽象类的介绍
抽象类使用的注意事项和细节讨论
01:
package AbstractDemo01;public class AbstractDetail01 {public static void main(String[] args){//A a = new A();//Error}
}abstract class A{//public abstract int n1 = 1;//ERROR//抽象类可以没有抽象方法public void hi(){System.out.println("hi");}}
01:
package AbstractDemo01;public class AbstractDetail02 {public static void main(String[] args){}
}abstract class D
{public int n1 = 10;public static String name = "dada";public void hi(){System.out.println("j1");}public abstract void hello();public static void ok(){System.out.println("ok");}
}
02:
public class AbstractDetail02 {public static void main(String[] args){}
}abstract class E
{public abstract void hi();
}abstract class F extends E{}class G extends E
{@Overridepublic void hi() {}
}
小练习
01:
02:
package AbstractDemo0102;public class AbstractExercise01 {public static void main(String[] args){Manager jack = new Manager("jack", 99, 50000);jack.setBonus(8000);jack.work();CommonEmployee tom = new CommonEmployee("tom", 888, 20000);tom.work();}}//===================================================package AbstractDemo0102;abstract public class Employee {private String name;private int age;private double salary;public Employee(String name, int age, double salary) {this.name = name;this.age = age;this.salary = salary;}public abstract void work();public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}
}//===========================================package AbstractDemo0102;public class Manager extends Employee{private double bonus;public Manager(String name, int age, double salary) {super(name, age, salary);}public double getBonus() {return bonus;}public void setBonus(double bonus) {this.bonus = bonus;}@Overridepublic void work() {System.out.println("manager = "+getName());}
}//==================================================package AbstractDemo0102;public class CommonEmployee extends Employee{public CommonEmployee(String name,int id,double salary){super(name,id,salary);}@Overridepublic void work() {System.out.println("Common worker = "+getName()+"working...");}}
抽象类最佳实践-模板设计模式
01:
package AbstractDemo03;public class TestWork01 {public static void main(String [] args){AA aa = new AA();aa.calculatTime();BB bb = new BB();bb.calculatTime();}
}//===============================================package AbstractDemo03;abstract public class Template {public abstract void job();public void calculatTime(){long start = System.currentTimeMillis();//单位是msjob();//动态绑定long end = System.currentTimeMillis();System.out.println("time = "+(end-start));}
}//=============================================package AbstractDemo03;public class AA extends Template {public void job(){long num = 0;for (long i = 1;i<=1000000000;i++){num+=i;}}
}//================================================package AbstractDemo03;public class BB extends Template{public void job(){long num = 0;for (long i = 1;i<=8000000;i++) {num *= i;}}
}
接口
快速入门
01:
package InterfackDemo01;public class Interface01 {public static void main(String[] args){Camera camera = new Camera();Phone phone = new Phone();Computer computer = new Computer();computer.work(phone);computer.work(camera);// phone work
// phone stop
// Camera work
// Camera stop}
}//===========================================package InterfackDemo01;public class Camera implements UsbInterFace{@Overridepublic void stopWork() {System.out.println("Camera stop");}@Overridepublic void startWork() {System.out.println("Camera work");}
}//================================================package InterfackDemo01;public class Computer {public void work(UsbInterFace usbInterFace){usbInterFace.startWork();usbInterFace.stopWork();}
}//================================================package InterfackDemo01;public class Phone implements UsbInterFace{@Overridepublic void startWork() {System.out.println("phone work");}@Overridepublic void stopWork() {System.out.println("phone stop");}
}//==================================================package InterfackDemo01;public interface UsbInterFace {public void startWork();public void stopWork();
}
基本介绍
01:
package InterfackDemo01;public class Interface02 {public static void main(String[] args){}
}class A implements AInterface
{public void hi() {System.out.println("hi()...");}
}//==================================package InterfackDemo01;public interface AInterface {public int n1 = 10;//在接口中,抽象方法,可以省略abstract关键字public void hi();//public abstract void hi();// public void ok()
// {
// System.out.println("ok.....");
// } ERROR,要加default关键字default public void ok(){System.out.println("ok....");}public static void cry(){System.out.println("cry....");}}
深入讨论
01:
package InterfackDemo01;public class InterFaceDemo {public static void main(String [] args){MysqlDB mysqlDB = new MysqlDB();OracleDB oracleDB = new OracleDB();InterFaceDemo interFaceDemo = new InterFaceDemo();interFaceDemo.t(mysqlDB);interFaceDemo.t(oracleDB);// connect
// close
// O connect
// B close}public void t(DBInterface db){db.connect();db.close();}
}//====================================================package InterfackDemo01;public class MysqlDB implements DBInterface{@Overridepublic void connect() {System.out.println("connect");}@Overridepublic void close() {System.out.println("close");}
}//====================================================package InterfackDemo01;public class OracleDB implements DBInterface{@Overridepublic void connect() {System.out.println("O connect");}@Overridepublic void close() {System.out.println("B close");}
}//======================================================package InterfackDemo01;public interface DBInterface {public void connect();public void close();
}
注意事项和细节
- 接口不能被实例化
- 接口中所有的方法是public方法,接口中抽象方法可以不用abstract修饰
- 一个普通类实现接口,就必须将该接口的所有方法都实现,可以使用alt+enter来解决
- 抽象类实现接口,可以不用实现接口的方法
- 一个类可以同时实现多个接口
- 接口中的属性,只能是final的,而且是public static final修饰符。比如:int a = 1;实际上是public static final int a = 1;(必须初始化)
- 接口中属性的访问形式:接口类.属性名
- 一个接口不能继承其他的类,但是可以继承多个别的接口 interface A extends B,C{}
- 接口的修饰符只能是public或默认,这点和类的修饰符是一样的
小练习
实现接口VS继承类
01:
package MonkeyDemo;public class ExtendsVSInterface {public static void main(String[] args){LittleMonkey wukong = new LittleMonkey("wukong");wukong.climbing();wukong.swimming();wukong.frying();}
}interface Fishable
{void swimming();
}interface Birdable
{void frying();
}class Monkey
{public String getName() {return name;}public Monkey(String name) {this.name = name;}private String name;public void climbing(){System.out.println("Monkey can climbing");}
}class LittleMonkey extends Monkey implements Fishable,Birdable{public LittleMonkey(String name) {super(name);}@Overridepublic void swimming() {System.out.println(getName()+"can swim by learning");}@Overridepublic void frying() {System.out.println(getName()+"can fry by learning");}
}
tip:
- 当子类继承了父类,就自动的拥有父类的功能,如果子类需要扩展功能,可以通过实现接口的方式来扩展,可以理解,实现接口,是对java单继承机制的一种补充
接口的多态特性
接口的多态体现:
- 接口类型的变量可以指向实现了这个接口的对象实例
继承体现的多态:
- 父类类型的变量可以指向继承它的子类的对象实例
01:
package MonkeyDemo;public class InterfacePolyParameter {public static void main(String[] args){IF if01 = new Monster();if01 = new Car();AAA a = new BBB();a = new CCC();}
}class AAA{}class BBB extends AAA{}class CCC extends AAA{}interface IF{}class Monster implements IF{}
class Car implements IF{}
02:
package MonkeyDemo;public class InterfacePolyArr {public static void main(String[] args){Usb[] usbs = new Usb[2];usbs[0] = new Phone();usbs[1] = new Camera();for (int i = 0;i<usbs.length;i++){usbs[i].work();if (usbs[i] instanceof Phone){((Phone)usbs[i]).call();}}// Phone can work
// Phone can call
// Camera can work}
}interface Usb{void work();
}class Phone implements Usb{public void call(){System.out.println("Phone can call ");}@Overridepublic void work() {System.out.println("Phone can work");}
}class Camera implements Usb{@Overridepublic void work() {System.out.println("Camera can work");}
}
03:
package MonkeyDemo;public class InterfacePolyPass {public static void main(String[] args){IG ig = new Teacher();IH ih = new Teacher();}
}interface IH{}
interface IG extends IH{}class Teacher implements IG{}
小练习
内部类
01:
package MonkeyDemo;public class InnerClass {//外部其他类public static void main(String[] args){}
}class Outer//外部类
{private int n1 = 100;public Outer(int n1){this.n1 = n1;}public void m1(){System.out.println("m1()");}{System.out.println("codeBlock");}class Inner{//内部类}
}
内部类的分类
局部内部类的使用
01:
package LocalInnerClass;public class LocalInnerClass {public static void main(String[] args){}}class Outer02
{private int n1 = 100;public void m1(){class Inner02{public void f1(){System.out.println("n1 = "+n1);}}}class Inner03 extends Inner02{}
}
02:
public class LocalInnerClass {public static void main(String[] args){}}class Outer02
{private int n1 = 100;public void m1(){//public class Inner02//errorfinal class Inner02//无法被继承{public void f1(){System.out.println("n1 = "+n1);}}}
}
03:
package LocalInnerClass;public class LocalInnerClass {public static void main(String[] args){Outer02 outer02 = new Outer02();outer02.m1();System.out.println("outer02的hashcode = "+outer02);}// n1 = 800 Outer n1 = 100
// Outer02.this hashcode = LocalInnerClass.Outer02@5fd0d5ae
// Outer02 m2()
// outer02的hashcode = LocalInnerClass.Outer02@5fd0d5ae}class Outer02
{private int n1 = 100;public void m2(){System.out.println("Outer02 m2()");}public void m1(){final class Inner02{private int n1 = 800;public void f1(){System.out.println("n1 = "+n1+" Outer n1 = "+Outer02.this.n1);System.out.println("Outer02.this hashcode = "+Outer02.this);m2();}}Inner02 inner02 = new Inner02();inner02.f1();}}
匿名内部类本质
01:
package AnnoymousInnerClass;public class AnonymousInnerClass {public static void main(String[] args){
// Cat cat = new Cat();
// cat.cry();AAA cat = new AAA() {@Overridepublic void cry() {System.out.println("cry()...");}};cat.cry();System.out.println(cat.getClass());// cry()...
// class AnnoymousInnerClass.AnonymousInnerClass$1}
}interface AAA
{public void cry();
}class Cat implements AAA{public void cry(){System.out.println("cry。。。");}
}
02:
package AnnoymousInnerClass;public class InnerWorkDemo {public static void main(String[] args){Father father = new Father("jack"){@Overridepublic void work() {System.out.println("work");}};father.work();System.out.println(father.getClass());// work
// class AnnoymousInnerClass.InnerWorkDemo$1}
}class Father
{public Father(String name){}public void work(){}
}//======================================================package AnnoymousInnerClass;public class InnerWorkDemo {public static void main(String[] args){Father father = new Father("jack");father.work();System.out.println(father.getClass());
// class AnnoymousInnerClass.Father}
}class Father
{public Father(String name){}public void work(){}
}//===================================================package AnnoymousInnerClass;public class InnerWorkDemo {public static void main(String[] args){Animal animal = new Animal(){@Overridevoid eat() {System.out.println("animal eat");}};animal.eat();//animal eat}
}abstract class Animal
{abstract void eat();
}
匿名内部类的使用
01:
package AnnoymousInnerClass;public class AnonymousInnerClassDetail {public static void main(String[] args){Outer05 outer05 = new Outer05();outer05.f1();//hi()....}
}class Outer05
{private int n1 = 99;public void f1(){Person person = new Person(){@Overridepublic void hi() {System.out.println("hi()....");}};person.hi();//动态绑定了,运行类型是Outer05$1}
}class Person
{public void hi(){System.out.println("Person hi()");}
}//==================================================package AnnoymousInnerClass;public class AnonymousInnerClassDetail {public static void main(String[] args){Outer05 outer05 = new Outer05();outer05.f1();//hi()....}
}class Outer05
{private int n1 = 99;public void f1(){//class 匿名内部类 extends Person{}new Person(){@Overridepublic void hi() {System.out.println("hi()....");}@Overridepublic void ok(String str) {super.ok(str);}}.ok("jack");}
}class Person
{public void hi(){System.out.println("Person hi()");}public void ok(String str){System.out.println("Person ok()"+str);}
}
02:
package AnnoymousInnerClass;public class AnonymousInnerClassDetail {public static void main(String[] args){Outer05 outer05 = new Outer05();outer05.f1();//hi()....System.out.println("hashcode = "+outer05);// hi()....10
// Outer 99
// Outer05 hashcode = AnnoymousInnerClass.Outer05@6d03e736
// hashcode = AnnoymousInnerClass.Outer05@6d03e736}
}class Outer05
{private int n1 = 99;public void f1(){//class 匿名内部类 extends Person{}Person p = new Person(){private int n1 = 10;@Overridepublic void hi() {System.out.println("hi()...."+n1);System.out.println("Outer "+Outer05.this.n1);//Outer05.this就是调用f1的对象System.out.println("Outer05 hashcode = "+Outer05.this);}// @Override
// public void ok(String str) {
// super.ok(str);
// }};p.hi();}
}class Person
{public void hi(){System.out.println("Person hi()");}public void ok(String str){System.out.println("Person ok()"+str);}
}
匿名内部类的最佳实践
01:
package AnnoymousInnerClass;public class InnerClassWork01 {public static void main(String[] args){//当做实参直接传递,简洁高效f1(new IA() {@Overridepublic void show() {System.out.println("this is famous picture");}});//传统方式f1(new Car());// this is famous picture
// this is famous picture!}public static void f1(IA ia){ia.show();}
}interface IA
{void show();
}class Car implements IA{@Overridepublic void show() {System.out.println("this is famous picture!");}
}
02:
package AnnoymousInnerClass;public class ADemo01 {public static void main(String [] args){CellPhone cellPhone = new CellPhone();cellPhone.alarmclock(new Bell() {@Overridepublic void ring() {System.out.println("lazy pig has got up");}});cellPhone.alarmclock(new Bell() {@Overridepublic void ring() {System.out.println("partner has haven a class");}});}
}interface Bell
{void ring();
}class CellPhone
{public void alarmclock(Bell bell){bell.ring();}
}
成员内部类的使用
01:
package AnnoymousInnerClass;public class MemberInnerClass {public static void main(String[] args){Outer08 outer08 = new Outer08();outer08.t1();}
}class Outer08
{private int n1 = 10;public String name = "zhan3";class Inner08{public void say(){System.out.println("n1 = "+n1+" name = "+name);}}public void t1(){Inner08 inner08 = new Inner08();inner08.say();}
}//===================================================package AnnoymousInnerClass;public class MemberInnerClass {public static void main(String[] args){Outer08 outer08 = new Outer08();outer08.t1();}
}class Outer08
{private int n1 = 10;public String name = "zhan3";//example:protected class Inner08{public void say(){System.out.println("n1 = "+n1+" name = "+name);}}public void t1(){Inner08 inner08 = new Inner08();inner08.say();}
}
02:
package AnnoymousInnerClass;public class MemberInnerClass {public static void main(String[] args){Outer08 outer08 = new Outer08();outer08.t1();//外部其他类,使用成员内部类的三种方式//1.Outer08.Inner08 inner08 = outer08.new Inner08();//2.Outer08.Inner08 inner08Instance = outer08.getInner08Instance();//3.Outer08.Inner08 inner081 = new Outer08().new Inner08();}
}class Outer08
{private int n1 = 10;public String name = "zhan3";private void hi(){System.out.println("hi()方法...");}public class Inner08{private int n3 = 20;public void say(){System.out.println("n1 = "+n1+" name = "+name);hi();}}public void t1(){Inner08 inner08 = new Inner08();inner08.say();int a = inner08.n3;System.out.println(a);}public Inner08 getInner08Instance(){return new Inner08();}
}
静态内部类的使用
01:
package StaticInnerClass01;public class StaticInnerClass01 {public static void main(String[] args){}
}class Outer10
{private int n1 = 10;private static String name = "zhan3";static class Inner10{public void say(){//System.out.println(n1);//Error static class 无法访问 非静态变量System.out.println(name);}}
}
02:
package StaticInnerClass01;public class StaticInnerClass01 {public static void main(String[] args){}
}class Outer10
{private int n1 = 10;private static String name = "zhan3";private static class Inner10{public void say(){System.out.println(name);}}
}
03:
package StaticInnerClass01;public class StaticInnerClass01 {public static void main(String[] args){Outer10 outer10 = new Outer10();outer10.m1();}
}class Outer10
{private int n1 = 10;private static String name = "zhan3";static class Inner10{public void say(){System.out.println(name);}}public void m1(){Inner10 inner10 = new Inner10();inner10.say();}}
04:
package StaticInnerClass01;public class StaticInnerClass01 {public static void main(String[] args){Outer10 outer10 = new Outer10();outer10.m1();//外部其他类 使用静态内部类//1.Outer10.Inner10 inner10 = new Outer10.Inner10();inner10.say();//2.Outer10.Inner10 instance = outer10.getInstance();}
}class Outer10
{private int n1 = 10;private static String name = "zhan3";static class Inner10{public void say(){System.out.println(name);}}public void m1(){Inner10 inner10 = new Inner10();inner10.say();}public Inner10 getInstance(){return new Inner10();}}
小练习
输出结果:
5
5