java中 this,final,super关键字

1.this关键字

(1) this表示当前类的实例化对象。

(2)  this调用本类中的属性,如果本类中没有此属性,将从父类中继续查找。

(3)  this调用本类中的方法,如果本类中没有此方法,将从父类中继续查找。

(4) this可以调用本类中的构造方法。

class person{
	protected String name;
	protected int age;
	protected int num;
	
	public person(String name){
		this.name=name;
	}
	//调用自身的构造方法,这种写法只能存在于构造方法中,在一个构造方法中有且只能有一个,在此构造方法中必须写在其他语句之前
	public person(String name, int age){
		this(name);
		this.age=age;
	}
	
	public person(String name, int age,int num){		
		this(name,age);		
		this.num=num;
	}
	
}

   匿名类或者内部类中要调用外部类方法,要使用:外部类名.this.方法名。

   this与static势不两立,应为static跟具体对象没有关系,this就是具体对象的引用。

2.final关键字

(1使用final修饰属性,表示常量,可以直接赋值或构造方法中赋值。

2使用final修饰方法,表示该方法不能被重写,但是可以被继承。(修饰符为private的除外)

3)使用final修饰类,表示该类不能被继承。

4)在方法参数中使用final,在该方法内部不能修改参数的值。

   使用final方法的原因:   

(1)把方法锁定,防止任何继承类修改它的意义和实现。

(2)高效。编译器在遇到调用final方法时会转入内嵌机制,大大提高执行效率。

3.super关键字

   (1)  super 表示父类对象的一个引用。

   (2) super 可以调用父类的属性和方法和构造方法。

    上代码

public class test{

  public static void main(String[] agrs){
		student s =new student("张三");
		s.talk();
		s.say();
		
  }
}

class person{
	protected String name;
	protected int age=10;	
	
	public person(String name){
		this.name=name;
	}
	
	public person(String name,int age){
		this.name =name;
		this.age=age;
	}
	
	protected void desc(){
		System.out.print("这是父类的方法");
	}
	
}

class student extends person{
	public int age=20;
	//注意,在构造方法中调用父类的构造方法用法和上面this用法一样。而且子类中定义带参的构造方法必须调用父类相同参数的带参构造方法!!!
	public student(String name){
		super(name);
	}
	
	public student(String name,int age){
		super(name,age);
	}
	
	public void talk(){
		System.out.println(age);
	}
	
	public void say(){
		System.out.println(super.age);
		super.desc();
	}

}


打印结果为:20

                        10

                         这个是父类的方法









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值