动手动脑2

p11:

代码:

package demo;

public class Show
{

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Parent parent=new Parent();
  parent.printValue();
  Child child=new Child();
  child.printValue();
  parent=child;
  parent.printValue();
  parent.myValue++;
  parent.printValue();
  ((Child)parent).myValue++;
  parent.printValue();
 }

}
class Parent{
 public int myValue=100;
 public void printValue(){
  System.out.println("Parent.printValue(),myValue="+myValue);
 }

}
class Child extends Parent
{
 public int myValue=200;
 public void printValue(){
  System.out.println("Child.printValue(),myValue="+myValue);
 }

运行结果:

Parent.printValue(),myValue=100
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=201 

结果解释:

首先创建了父类对象parent,parent调用父类printValue方法,输出100。然后创建了子类对象childchild调用子类printValue方法,输出200。接着把子类对象赋值给父类对象,赋值后的parent.printValue();即相当于child.printValue();所以输出200。被赋值后的父类对象对数据成员的操作依然是对父类的数据成员进行操作,并没有对子类数据成员进行操作,所以parent.myValue++,只是将父类的myValue+1,而子类的myValue值并没有改变,所以 parent.printValue();输出200((Child)parent).myValue++;使用了强制类型转换,即结果是对子类的myValue+1,而parent已经被子类对象赋值,所以parent.printValue()输出201

语法特性:

 

当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定。如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段),也就是覆盖。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。如果子类被当做父类使用,通过子类访问的字段是父类的。

p24:

运行结果:

ArrayIndexOutOfBoundsException/内层try-catch

 

发生ArithmeticException

p25:

运行结果:ArrayIndexOutOfBoundsException/外层try-catch

p26:

运行结果:

in Level 1
in Level 2
in Level 3
Level 3:class java.lang.ArithmeticException
In Level 3 finally
In Level 2 finally
In Level 1 finally

不管是否有异常发生,finally中的语句始终会被执行。

p27:

运行结果:

in main
Exception is thrown in main

finally语句块中有System.out.println(0),没有被执行。

posted @ 2015-11-15 19:47  牙吃多了糖疼  阅读(106)  评论(0编辑  收藏  举报