子类可以继承父类的protected、default、public变量。而private不能继承。这个很简单,直接看代码。
package extend; public class ParentClass { private String privateVariable = "private Variable"; protected String protectedVariable = "protected Variable"; String defaultVariable = "default Variable"; public String publicVariable = "public Variable"; private static String privateStaticVariable = "private Static Variable"; protected static String protectedStaticVariable = "protected Static Variable"; static String defaultStaticVariable = "dafault Static Variable"; public static String publicStaticVariable = "publicStatic Variable"; public ParentClass() { System.out.println("default parent class"); } public ParentClass(String str) { System.out.println("parent class " + str); } } public class SubClass extends ParentClass { public SubClass(){ System.out.println("default sub class"); // System.out.println("sub class print : " + privateVariable); System.out.println("sub class print : " + protectedVariable); System.out.println("sub class print : " + defaultVariable); System.out.println("sub class print : " + publicVariable); // System.out.println("sub class print : " + privateStaticVariable); System.out.println("sub class print : " + protectedStaticVariable); System.out.println("sub class print : " + defaultStaticVariable); System.out.println("sub class print : " + publicStaticVariable); } public SubClass(String str){ super(str); System.out.println("sub class " + str); } public static void main(String[] args) { SubClass subClass = new SubClass(); new SubClass("A"); } }
运行结果:
default parent class
default sub class
sub class print : protected Variable
sub class print : default Variable
sub class print : public Variable
sub class print : protected Static Variable
sub class print : dafault Static Variable
sub class print : publicStatic Variable parent
class A
sub class A
代码导读:
在父类中定义private,protected,default,public变量。在子类中直接访问。
结论:
从运行结果可以得到,
在子类中可以直接访问protected,default,public属性。子类直接把父类的这三种变量当成自己的变量了。呵呵。父类的private变量可以通过getter和setter方法访问。