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

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());
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值