class Sundae{
//以下两个方法缺省为friendly
Sundae(){}
Void f() {System.out.println(“Sundae.f()”);
}
public class IceCream{
public static void main(String[] args){
Sundae x = new Sundae();
x.f();
}
}
class Sundae{
private Sundae(){}//只能在Sundae class中被调用
Sundae(int i) {}
static Sundae makASundae() {
return new Sundae();
}
}
public class IceCream{
public static void main(String[] args){
// Sundae class中构造函数Sundae()是private,
// 所以不能用它进行初始化
//Sundae x = new Sundae();
Sundae y = new Sundae(1);//Sundae(int)是friendly,可以在此调用
Sundae z = Sundae.makASundae();
}
}
import pack1.Cookie;
//注意:在这里ChocolateChip继承了类Cookie,按道理bite()方法也在
//ChocolateChip中,可以用x.bite直接调用,但是不可以的,因为类ChocolateChip
//和Cookie类不在一个包中,各自具有包访问权限,为了能够使用x.bite()必须要把
//Cookie方法的访问权限换成public或者protected,但是一旦换成public所有的人就
//可以访问了,这样达不到隐私的要求,所以设置成protected最好,既可以顺利访问,也可以
//避免外面的类调用,保护好隐私的作用
public class ChocolateChip extends Cookie {
public ChocolateChip() {
System.out.println("ChocolateChip constructor");
}
public static void main(String[] args) {
ChocolateChip x = new ChocolateChip();
x.bite(); // Can't access bite
}
} ///:~
package pack1;
public class Cookie {
public Cookie()
{
System.out.println("Cookie constructor");
}
protected void bite(){System.out.println("bite");}
}
对于类来说:类不可以声明为protected
package Number;
import Test.*;
public class Frist extends Test
{
protected String s1 = "你好";
public static void main( String[] args)
{
String s2 = "java";
//System.out.println(s1);
System.out.println(s2);
Frist t = new Frist();
System.out.println(t.s);
t.show();
return;
}
}
Test.java:
package Test;
public class Test
{
protected String s = "hello test"; //可以被同包中的类访问以及子类访问,该子类可以是与包Test不同
public void show()
{
Test1 t1 = new Test1();
return;
}
}
class Test1
{
Test1()
{
Test t = new Test();
System.out.println(t.s);
}
}
java hello test hello test
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有