黑马程序员技术交流社区
标题:
super和this关键字怎么用?
[打印本页]
作者:
闵霞
时间:
2012-8-25 09:42
标题:
super和this关键字怎么用?
package com.ket.cor;
import org.henan.util.*;
class AnimalS{
String sex;
public AnimalS(){
this("male");
System.out.println("This is the outline of Animal ! no param");
}
public AnimalS(String str){
this.sex = str;
System.out.println(this.sex);
System.out.println("Have parameters !");
}
public void eat(){
System.out.println("Have no special");
}
public String getSex(){
return this.sex;
}
public void setSex(String sex){
this.sex = sex;
}
}
class Person extends AnimalS{
private String name;
private int age;
String sex;
public Person(){
super();
System.out.println("This is subclass !");
this.name = "tom";
this.age = 20;
this.sex = "nv";
}
public void exc(){
System.out.println(this.name);
System.out.println(this.age);
System.out.println(getSex());
setSex("female");
System.out.println(getSex());
}
}
public class TestAnimalS{
public static void main(String[] args){
Person pr = new Person();
pr.exc();
pr.setSex("nan");
System.out.println(pr.getSex());
pr.eat();
System.out.println(pr.sex);
//System.out.println(super.sex);
}
}在main里面不可以用this和super指代新创建的类和父类吗?新创建的类里面,如果方法是继承的,且有相同变量,调用父类方法改变此变量就只能改变父类里面的此变量,而不能改变子类里面的变量,为什么呢?
作者:
王小刚
时间:
2012-8-25 09:55
1.
main 因为是static静态的,不能指示新创建的类和父类
this(有参数/无参数) 用于调用本类相应的构造函数
super(有参数/无参数) 用于调用父类相应的构造函数
this. 后跟方法或属性 指示本类的方法或属性
super. 后跟方法或属性(父类中指明的public protected)
2.
调用父类方法改变此变量就只能改变父类里面的此变量,而不能改变子类里面的变量,为什么呢?
调用父类的方法改变的变量只能是父类的变量这是必然的,因为父类中不存在子类新加的变量,因此只能改变父类中的变量
作者:
高廷平
时间:
2012-8-25 10:41
super()调用父类构造方法或成员
this.XXX:指代当前对象
作者:
刘源
时间:
2012-8-25 10:42
楼上说的很好了,我补充下:
super()与this()的区别
This():当前类的对象,super父类对象。
Super():在子类访问父类的成员和行为,必须受类继承规则的约束
而this他代表当前对象,当然所有的资源都可以访问.
在构造函数中,如果第一行没有写super(),编译器会自动插入.但是如果父类没有不带参数的构造函数,或这个函数被私有化了(用private修饰).此时你必须加入对父类的实例化构造.而this就没有这个要求,因为它本身就进行实例化的构造.
而在方法中super和this使用的方法就差不多了.只不过super 要考虑是否能访问其父类的资源.
当然这里有个特例。比如说:
public class Test extends Date{
public static void main(String[] args) {
new Test().test();
}
public void test(){
System.out.println(this.getClass().getName());
System.out.println(getClass().getName());
System.out.println(super.getClass().getName());
}
}
这3个打印的都是Test。
因为所以类的最终父类都是Object,如果该方法
getClass()
是Object中的方法,并且被final修饰之后,
子类不能覆盖它。
所以子类调用该方法,都是父类的方法,不管是否有
this和super修饰。
作者:
黑马杨晨
时间:
2012-8-25 11:48
class Demo
{
public static void main(String[] args)
{
System.out.println("建议大家使用此工具");
}
}
复制代码
好像很少人使用插入代码工具!
捕获.PNG
(5.81 KB, 下载次数: 56)
下载附件
2012-8-25 11:48 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2