java笔记(super关键字的使用)

  • 格式:doc
  • 大小:67.37 KB
  • 文档页数:3

下载文档原格式

  / 3
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

super 关键字的使用 super 关键字出现在子类中,主要功能就是完成子类调用父类中的内容,也就是调用父类中的属性或方法。

super 调用父类中的构造方法:

class Person

{

String name;

int age;

public Person(String name,int age)

{

=name;

this.age=age;

}

}

class Student extends Person

{

String school;

public Student()

{

super("张三",27);

}

}

public class TestPersonStudentDemo

{

public static void main(String args[])

{

Student s=new Student();

S.shchool=”北京”;

System.out.println("我是:"++",今年:"+s.age+"岁,学校:"+s.school) ; }

}

输出结果为:我是张三,今年27岁,学校:北京

本程序在子类的构造方法中明确地指明了调用的是父类中有两个参数的构造方法,所以程序在编译时不再去找父类中无参的构造方法。

用super 调用父类中的构造方法,只能放在子类的第一行。

通过super 调用父类的属性和方法:

class Person 父类构造方法

子类构造方法 调用父类构造方法

{

String name;

int age;

public Person()

{

}

public String talk()

{

return "我是:"++",今年:"+this.age+"岁";

}

}

class Student extends Person

{

String school;

public Student(String name,int age,String school)

{

//在这里用super 调用父类中的属性

=name;

super.age=age;

//调用父类中的talk()方法

System.out.print(super.talk());

//调用本类中属性

this.school=school;

}

}

public class TestPersonStudentDemo3

{

public static void main(String args[])

{

Student s=new Student("张三",27,"北京");

System.out.println(",学校:"+s.school);

}

}

输出结果为:

我是:张三,今年:27岁,学校:北京

限制子类的访问

有些时候,父类并不希望子类可以访问自己的类中全部的属性或方法,所以需要将一些属性父类构造方法

子类构造方法 父类一般方法

与方法隐藏起来,不让子类去使用。为此,可在声明属性或方法时加上“private”关键字,表示私有。

class Person

{

private String name;

private int age;

}

class Student extends Person

{

public void setVar()

{

name="张三";

age=27;

System.out.println(name+age);

}

}

class TestPersonStudentDemo

{

public static void main(String args[])

{

Student s=new Student();

s.setVar();

}

}

输出结果为:

Exception in thread "main" ng.Error: 无法解析的编译问题:

字段 不可视

字段Person.age 不可视

字段 不可视

字段Person.age 不可视

at exercise1.Student.setVar(TestPersonStudentDemo.java:11)

at exercise1.TestPersonStudentDemo.main(TestPersonStudentDemo.java:21)