您的位置:首页 > 编程语言 > Java开发

Java基础重温(五)类,接口

2013-07-10 22:01 351 查看
1.final关键字

a.final可修饰类、成员变量、方法中的参数

b.final修饰的类不能被继承,即不可能有子类

c.final修饰的方法不能被重写(可以被子类继承)

d.final修饰的成员变量是常量,必须给初始值,而且不能被改变

e.final修饰的方法里的参数的值不可改变

2.interface

接口中的成员变量都是public final static的,成员方法都是public abstract的,如果不说明,这都是默认的(如果变量用private修饰或者变量不赋给初始值则会报错)

3.内部类

a.内部类前修饰符可为private,友好型,protected,public,也可以用fianl,static等关键字修饰

b.表明为某个对象的格式:OuterClassName.InnerClassName.

c.内部类的成员和方法为什么不能用static?因为内部类对象,要与外部类对象相关联才能被建立(会回去指向外部类对象的引用).

d.当给一个内部类传递参数时,如果这个参数在内部类中被直接使用,则这个参数一定是final的,e.g.

public class Parcel3 {
    // argments "dest", "price", must be final!
    public Destination getDestination(final String dest, final float price, String str) {
        return new Destination() {
            private int cost;
            {
                cost = Math.round(price);
                if(cost > 100) {
                    System.out.println("Over buget!");
                    // System.out.println(str); --error:
                    // local variable str is accessed from within inner class;
                    // needs to be declared final.
                }
            }
            
            private String label = dest;
            public String readLabel() {
                return label;
            }
        };
    }
    
    public static void main(String[] args) {
        Parcel3 p3 = new Parcel3();
        Destination d = p3.getDestination("qidong", 1000, "test");
    }
}

e.内部类访问外部类的成员变量与方法: 1)如果内部类和外部类的变量或方法同名,则外部类的变量或方法会被覆盖,这时候需要用OuterClass.this.变量名来

访问外部的变量与方法 2)在内部类中用this指的是当前内部类这个对象 3)如果外部类所定义的变量或方法没有被内部类所覆盖,在内部类中直接用变量名

或方法即可访问,e.g.

public class Test03 {
	private String label = "outer label";
	private void outer() {
		System.out.println("outer method...");
	}
	public Destination getDestination() {
		return new Destination() {
			private String label = "inner label";
			{
				System.out.println(this.label); // inner label
				System.out.println(Test03.this.label); // outer label
				outer(); // overide, inner method...
				this.outer(); // inner method...
				Test03.this.outer(); // outer method...
				label = "lb";
			}	
			public String readLabel() {
				return label;
			}
			
			private void outer() {
				System.out.println("inner method...");
			}
		};
	}
	
	public static void main(String[] args) {
		Test03 test = new Test03();
		System.out.println(test.getDestination().readLabel());
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: