public,private and protected

1. when used to instance variables and mehods

For example we have the java code below:

//code1
package test;

public class TestA {

	private int i = 0;
		    int def = 0;			
	protected int pr = 0;
	public int pub = 3;

}

//code 2
package test2;
import test.TestA;

public class TestB {
	public static void main(String [] args){
		TestA a = new TestA();
		System.out.println(a.pub);//can only reference public variable
	}

}


//code3
package test2;
import test.TestA;

public class TestB extends TestA {
    public static void main(String [] args){
        TestB b = new TestB();
        System.out.println(b.pr);//can reference protected and public
    }

}

 So, we can get the conclusion here:  Some times we like use default, but this can bring problems, default can only offer the reference in the same package, in code2, TestB is in another package, we new an TestA but we can't get access to it's default variable def. 

If we want to get access of variables in another package( except public), we have to use extention and the protected field. So don't use default when writing code, if we want't this field be accessed in another package we have to name this variable as protected or public.

2. used for class(only public and default can be used)

public means this class can be accessed anywhere

default: means this class can only be accessed by other classes in the same package.

3. used for constructor methods

Sometimes when we are writing constructor, we often use public, or sometimes we use default. But if we use default key word, we may meet trouble when a class B extends from a class A in another package and A use default key word for constructor. when we initialize B, we may meet trouble.

package test;

public class TestA {

	private int value = 0;
	
	//use the default keyword
	TestA(){
		System.out.println("superclass()");
	}
	//also use default keyword
	TestA(int i){
		i = this.value;
		System.out.println("superclass("+i+")");
	}
	
}

package test2;
import test.TestA;

public class TestB extends TestA{
	
	//trouble here, cause we can't get access to super class's constructor
	public TestB() {
		System.out.println("testB()");
	}

	public static void main(String [] args){
		TestB b = new TestB();
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值