四种访问权限修饰符
- Java权限修饰符public、protected、 (缺省)、 private置于类的成员定义前,用来限定对象对该类成员的访问权限。
- 对于class的权限修饰只可以用public和default(缺省)。
- public类可以在任意地方被访问。
- default类只可以被同一个包内部的类访问。
访问控制举例(一)
class Parent{ private int f1 = 1; int f2 = 2; protected int f3 = 3; public int f4 = 4; private void fm1() {System.out.println("in fm1() f1=" + f1);} void fm2() {System.out.println("in fm2() f2=" + f2);} protected void fm3() {System.out.println("in fm3() f3=" + f3);} public void fm4() {System.out.println("in fm4() f4=" + f4);} }
访问控制举例(二)
class Child extends Parent{ //设父类和子类在同一个包内 private int c1 = 21; public int c2 = 22; private void cm1(){System.out.println("in cm1() c1=" + c1);} public void cm2(){System.out.println("in cm2() c2=" + c2);} public static void main(String[] args){ int i; Parent p = new Parent(); i = p.f2; // i = p.f3; i = p.f4; p.fm2(); // p.fm3(); p.fm4(); Child c = new Child(); i = c.f2; // i = c.f3; i = c.f4; i = c.c1; // i = c.c2; c.cm1(); // c.cm2(); c.fm2(); c.fm3(); c.fm4() } }
关键字:super
- 在Java类中使用super来调用父类中的指定操作:
- super可用于访问父类中定义的属性
- super可用于调用父类中定义的成员方法
- super可用于在子类构造器中调用父类的构造器
注意:
- 尤其当子父类出现同名成员时,可以用super表明调用的是父类中的成员
- super的追溯不仅限于直接父类
- super和this的用法相像,this代表本类对象的引用,super代表父类的内存空间的标识
关键字super举例
class protected Person { String name = "张三"; protected int age; public String getInfo() { return "Name: " + name + "\nage: " + age; } } class Student extends Person { protected String name = "李四"; private String school = "New Oriental"; public String getSchool() { return school; } public String getInfo() { return super.getInfo() + "\nschool: " + school; }} public class StudentTest { public static void main(String[] args) { Student st = new Student(); System.out.println(st.getInfo());
调用父类的构造器
- 子类中所有的构造器默认都会访问父类中空参数的构造器
- 当父类中没有空参数的构造器时,子类的构造器必须通过this(参数列表)或者super(参数列表)语句指定调用本类或者父类中相应的构造器。同时,只能”二选一”,且必须放在构造器的首行
- 如果子类构造器中既未显式调用父类或本类的构造器,且父类中又没有无参的构造器,则编译出错
调用父类构造器举例
public class Person { private String name; private int age; private Date birthDate; public Person(String name, int age, Date d) { this.name = name; this.age = age; this.birthDate = d; } public Person(String name, int age) { this(name, age, null); } public Person(String name, Date d) { this(name, 30, d); } public Person(String name) { this(name, 30); } }