1.Java的访问控制修饰符有哪些?各有什么访问权限?
public、private、protected。



同一个包——演示public类的protected属性访问:


![]()
不同包——演示public类的protected属性访问:


![]()
2、子类对于从父类继承的哪些属性与方法是可见的?请分别写程序进行验证。
父类的public和proected的属性与方法对子类来讲是可见的。


3、什么是组合?有什么作用?请举例说明。
组合是通过现有的对象进行拼装产生新的、更加复杂的功能。
1 class FighterPlane 2 { 3 String name; 4 int missileNum; 5 public FighterPlane(String _name,int _missileNum){ 6 name = _name; 7 missileNum = _missileNum; 8 } 9 public void fire(){ 10 if (missileNum>0){ 11 System.out.println("now fire a missile !"); 12 missileNum -= 1; 13 } 14 else{ 15 System.out.println("No missile left !"); 16 } 17 } 18 } 19 20 class A 21 { 22 FighterPlane fp; 23 public A(FighterPlane fpp){ 24 this.fp = fpp; //A对象中拥有了FighterPlane对象的引用 25 } 26 public void invoke(){ 27 //A中对象发送消息给FighterPlane的对象 28 System.out.println(fp.name); 29 } 30 } 31 public class Run{ 32 public static void main(String[] args) 33 { 34 FighterPlane ftp = new FighterPlane("su35",10); 35 //产生A对象,并将ftp对象引用作为参数传入 36 A a = new A(ftp); 37 //发送消息,产生调用关系 38 a.invoke(); 39 } 40 }
4、什么是重载?有什么作用?请举例说明。
重载:方法名称相同,参数类型或个数不同。重载可以对其功能进行复用,同时又可以对其进行补充。
注意:若方法名称相同,参数相同,返回类型不同,则编译不能通过。
1 class Parent{ 2 public int getScore(){ 3 return 3; 4 } 5 public int getScore(int i){ 6 return i; 7 } 8 }
5、什么是覆盖?有什么作用?请举例说明。
子类对父类的同名方法(方法名称相同,参数相同,返回类型相同)重新进行定义,即在子类中定义与父类中已定义的同名而内容不同的方法。
覆盖与引用替换结合,可使抽象类的声明在保证消息发送统一性的前提下,具有消息结果执行上的差异性特点。
1 class Parent { 2 public int getScore() 3 { return 3; } 4 public String getCountryName() 5 { return “China”; } 6 } 7 class Son extends Parent { 8 public int getScore(){ 9 return 4; 10 } 11 } 12 public class RunSon{ 13 public static void main(String args[]){ 14 Son s = new Son(); 15 System.out.println(s.getScore()); 16 System.out.println(s.getCountryName()); 17 } 18 } 19 //输出结果 4 ,China
浙公网安备 33010602011771号