面向对象(下)

来源:互联网 发布:淘宝买家延长收货几天 编辑:程序博客网 时间:2024/05/16 08:38

一、在类中,声明为static的成员变量为静态成员变量,它为该类的公用变量,对所有对象来说,它在内存只有一份;在static的静态方法中不会将对象引用传递给他,因此,静态方法不能访问非静态成员;可以通过对象引用和类名来访问静态成员变量。

class Cat{    public static int sid = 0;    private int id ;    private String name;    Cat2(String name){        this.name = name;        id = sid++;    }    public void Info(){        System.out.println("My name is"+name +" NO."+id);    }}public class StaticTest {    public static void main(String[] args) {        Cat.sid = 100;        Cat c1 = new Cat("mimi");        Cat c2 = new Cat("pipi");        c1.Info();        c2.Info();    }}

这里写图片描述
二、构造代码块和静态代码块
(1)构造代码块:
构造代码块中定义的是给不同的对象共性的初始化内容。对象一建立就运行,优先于构造函数。
构造函数和构造代码块的区别:构造函数是给对应的对象初始化,而构造代码块是给所有对象进行统一的初始化。
(2)静态代码块
特点:随着类的加载而执行;只执行一次;优先于主函数执行。作用是对类初始化。静态代码块中无法对成员变量访问,除非是static类型的成员变量。

static{    }

三、内部类
1、内部内的访问规则
(1)内部类可以直接访问外部类中的成员,包括私有的。之所以能够直接访问,是因为内部类持有了一个外部类的引用,格式为:外部类名.this。
(2)外部类要访问内部类,必须建立内部类对象。
(3)如何创建内部类对象:new 外部类.new 内部类。

class Outer {    private int x = 1;    class Inner {        int x = 2;        void function() {            int x = 3;            System.out.println("Inner:" + Outer.this.x);            System.out.println("Inner:" + this.x);            System.out.println("Inner:" + x);        }    }    void methd() {        Inner in = new Inner();        in.function();    }}public class OuterDemo {    public static void main(String[] args) {       Outer ou = new Outer();       Outer.Inner in  = new Outer().new Inner();       in.function();       ou.methd();    }}

输出结果:

Inner:1Inner:2Inner:3Inner:1Inner:2Inner:3

2、静态内部类
在外部类的内部定义
特点:不能访问外部类的非静态成员。出现了访问局限。
(1)在外部其他类中如何访问静态内部类非静态成员?
new Outer.Inner().function();
(2)在外部其他类中如何访问静态内部类的静态成员?
Outer.Inner.function();
注意:(1)当内部类中定义了静态成员,该内部类必须声明为静态内部类。(2)、当外部类中的静态方法访问内部类时,内部类也必须是静态的。

3、匿名内部类

//定义接口interface AbsDemo{    public void show();}class ClassTest{    int x = 3;    //内部类的常规写法    /*class Inner implements AbsDemo{        public void show(){            System.out.println("x=" + x);        }    }    public void method() {        //调用内部类的show方法        new Inner().show();    }*/    //匿名内部类的写法:    public void method() {        AbsDemo d  = new AbsDemo(){            public void show(){                System.out.println("x=" + x);            }        };        d.show();    }}public class StringToInt {    public static void main(String[] args) {        ClassTest ct = new ClassTest();        ct.method();    }}

输出

x=3

总结一下匿名内部类的特点:

    ①匿名内部类是内部类的简写格式。换了一下写法而已。    ②定义匿名内部类的前提:    内部类必须是继承某个类或者实现某个接口.存在父类引用指向子类对象。    ③匿名内部类的格式:new 父类或者接口(){代码块}    ④其实匿名内部类就是一个匿名子类对象。    ⑤匿名内部类中定义的方法最好不要超过3个。
0 0