我恰巧也想问个这样的问题 public class TestExec{ public static void main(String[] args){ Student stu = new Student(); stu.show(); } } class People{ String name; private int age = 30;//私有属性 public void show(){ System.out.println(age); } } class Student extends People{}stu调用的show()到底是谁的方法?
http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4.3 The members of a class type (§8.2) are classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (§8.4.8).
protected : 保护成员,该类内部和继承类中可以访问。
public : 公共成员,完全公开,没有访问限制。
internal: 在同一命名空间内可以访问
public class TestExec{
public static void main(String[] args){
Student stu = new Student();
stu.show();
}
}
class People{
String name;
private int age = 30;//私有属性
public void show(){
System.out.println(age);
}
}
class Student extends People{}stu调用的show()到底是谁的方法?
The members of a class type (§8.2) are classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (§8.4.8).
1.那必须不是这样呀,你想想你把你的父类的属性设置为private的,然后不提供或者只提供一个private的方法来获得该属性,那你设计这个类属性就基本等同于在父类的所有方法里设计了一个可用的零时变量,因为只有在该父类里你可以访问该属性,但是这有什么意义呢,还不如用到哪个零时变量时自己再定义。
2.一般是把父类的属性设置为private的,然后提供一个public的方法可以获得该属性,这样父类就可以实现封装,子类可以继承父类属性和方法。
3.拓展:单例模式(Singleton),自己试着去研究下吧!那个是把构造方法设为私有的~~~
你在student里也声明一个age看看...
这是JAVA?还有一个是friendly 缺省
用private相当于子类有父类的拥有权,而没有使用权。