this、super关键字,代码块

一、关键字

    1.super关键字

        (1)调用父类的成员变量

        (2)调用父类的构造方法

        (3)调用父类的其他方法

    2.this关键字

        (1)调用本类的成员变量

        (2)调用本类的其他方法

        (3)在构造方法中调用其他构造方法

        (4)返回对象的值

    3.测试

	public static void main(String[] args) {
		
		Dog dog = new Dog();
		System.out.println(dog.speak());
	}
}

class Animal{
	
	String name = "Daniel";
	public void say(){
		System.out.println("我是一只动物。。。");
	}
	public Animal(){
		System.out.println("父类构造方法。。。");
	}
}

class Dog extends Animal{
	
	String name = "daniel";
	public Dog speak(){
		System.out.println("我是一条狗。。。");
		//this返回对象的值
		return this; 
	}
	
	public Dog(String name){
		//super调用父类的构造方法(必须在第一行,构造函数用于初始化)
		super();
		System.out.println("我的名字:"+name);
		//super调用父类的成员变量
		System.out.println(super.name);
		//super调用父类的其他方法
		super.say();
	}
	
	public Dog(){
		//this在构造方法中调用构造方法(必须在第一行)
		this("Daniel");
		//this调用本类中其他方法
		this.speak();
		//this调用本类的成员变量
		System.out.println(this.name);

	}	
	
}

 

 

二、代码块

1.构造代码块

解释:直接在类中定义且没有加static,在构造函数被调用时执行,且先于构造函数执行,给对象统一初始化。

        

2.静态代码块

解释:用static声明的代码块,用于初始化类的属性,只会执行一次,且先于main方法执行。

    测试:

    public static void main(String[] args) {
	new Test1();
	new Test2();
	new Test2();
	}
}

    class Test1{
	String name;
	{
	    this.name = "Daniel";
	    //构造代码块先于构造方法执行
	    System.out.println("构造代码块。。。");
	}
	public Test1(){
	    System.out.println("构造方法。。。");
	    System.out.println("初始化name:"+name);
	}
}

    class Test2{
	
	static int num ;
	
	static{
		num = 1;
		//只会输出一次(静态代码块只运行一次)
		System.out.println("静态代码块。。。");
	}
	public Test2(){
		System.out.println(num);
	}
}

结果:

构造代码块。。。
构造方法。。。
初始化name:Daniel
静态代码块。。。
1
1
1

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值