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
这个是父类的方法
本文详细解析了Java中this和super关键字的使用方法及注意事项,包括this在构造方法中的特殊用法、与static的区别,以及super如何调用父类属性和方法等内容。
361

被折叠的 条评论
为什么被折叠?



