Java继承中变量和方法在各访问权限下的情况

下面程序的可读性不怎么好,可以说比较差吧,就凑合着看吧,就为了理解一下。

 

package cn.lifx.test;

public class SubParTest 
{
	public static void main(String[] args)
	{
		ParentClass pc = new ParentClass();
		System.out.println(pc.publicValue);
		System.out.println(pc.friendlyValue);
		System.out.println(pc.protectedValue);
		System.out.println(pc.getPrivaeValue());
		pc.publicFun();
		pc.friendlyFun();
		pc.protectedFun();
		
		System.out.println();
		
		ParentClass psc = new SubClass();
		System.out.println(psc.publicValue);
		System.out.println(psc.friendlyValue);
		System.out.println(psc.protectedValue);
		System.out.println(psc.getPrivaeValue());
		psc.publicFun();
		psc.friendlyFun();
		psc.protectedFun();
		
		System.out.println();
		
		SubClass sc = new SubClass();
		System.out.println(sc.publicValue);
		System.out.println(sc.friendlyValue);
		System.out.println(sc.protectedValue);
		System.out.println(sc.getPrivaeValue());
		sc.publicFun();
		sc.friendlyFun();
		sc.protectedFun();
	}
}

class SubClass extends ParentClass
{
	public String publicValue = "sub_public_field";
	String friendlyValue = "sub_friendly_field";
	protected String protectedValue = "sub_protected_field";
	private String privateValue = "sub_private_field";
	
	public void publicFun()
	{
		System.out.println("sub_public_function()");
	}
	
	void friendlyFun()
	{
		System.out.println("sub_friendly_function()");
	}
	
	protected void protectedFun()
	{
		System.out.println("sub_protected_function()");
	}
	
	public String getPrivaeValue()
	{
		return this.privateValue;
	}
}

class ParentClass
{
	public String publicValue = "parent_public_field";
	String friendlyValue = "parent_friendly_field";
	protected String protectedValue = "parent_protected_field";
	private String privateValue = "parent_private_field";
	
	public void publicFun()
	{
		System.out.println("parent_public_function()");
	}
	
	void friendlyFun()
	{
		System.out.println("parent_friendly_function()");
	}
	
	protected void protectedFun()
	{
		System.out.println("parent_protected_function()");
	}

	public String getPrivaeValue()
	{
		return this.privateValue;
	}
}

 

 

输出为:

 

parent_public_field
parent_friendly_field
parent_protected_field
parent_private_field
parent_public_function()
parent_friendly_function()
parent_protected_function()

parent_public_field
parent_friendly_field
parent_protected_field
sub_private_field
sub_public_function()
sub_friendly_function()
sub_protected_function()

sub_public_field
sub_friendly_field
sub_protected_field
sub_private_field
sub_public_function()
sub_friendly_function()
sub_protected_function()

 

你可能感兴趣的:(java)