zoukankan      html  css  js  c++  java
  • 多态与异常处理(课后作业)

    1、finally语句块一定会执行吗? 请通过 SystemExitAndFinally.java示例程序回答上述问题

    代码:

    public class SystemExitAndFinally
    {

    public static void main(String[] args)

    {

    try
    {


    System.out.println("in main");

    throw new Exception("Exception is thrown in main");

    //System.exit(0);


    }

    catch(Exception e)

    {

    System.out.println(e.getMessage());

    System.exit(0);

    }
    finally

    {
    System.out.println("in finally");

    }

    }


    }

     截图:

    所以finally语句不一定执行。

    2、

    class Mammal{}
    class Dog extends Mammal {}
    class Cat extends Mammal{}

    public class TestCast
    {
    public static void main(String args[])
    {
    Mammal m;
    Dog d=new Dog();
    Cat c=new Cat();
    m=d;
    d=m;
    d=(Dog)m;
    //d=c;
    //c=(Cat)m;

    }
    }

    结果:

    结论:其中d=m d=c 会出错  d=m是把基类对象赋值给子类需要强制类型转换  d=c:d和c是两个不同的类的对象不能进行赋值运算

    3、


    public class ParentChildTest {
    public static void main(String[] args) {
    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其实是子类的类型,所以value++是加在了父类中而调用的函数是子类的所以输出的是子类的value为200

    4、

    public class CatchWho2 {
    public static void main(String[] args) {
    try {
    try {
    throw new ArrayIndexOutOfBoundsException();
    }
    catch(ArithmeticException e) {
    System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");
    }
    throw new ArithmeticException();
    }
    catch(ArithmeticException e) {
    System.out.println("发生ArithmeticException");
    }
    catch(ArrayIndexOutOfBoundsException e) {
    System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");
    }
    }
    }

    结论:第二个try抛出的警告被外层处理

  • 相关阅读:
    Problem E. Matrix from Arrays(杭电2018年多校第四场+思维+打表找循环节)
    Reachability from the Capital(Codeforces Round #490 (Div. 3)+tarjan有向图缩点)
    Network of Schools(POJ1326+有向图进行缩点)
    John's trip(POJ1041+欧拉回路+打印路径)
    Watchcow(POJ2230+双向欧拉回路+打印路径)
    Network(POJ3694+边双连通分量+LCA)
    Problem L. Visual Cube(杭电多校2018年第三场+模拟)
    floyd骚操作——传递闭包
    Remmarguts' Date(POJ2449+最短路+A*算法)
    Transformation(线段树+HDU4578+多种操作+鬼畜的代码)
  • 原文地址:https://www.cnblogs.com/jingjing0629/p/4967851.html
Copyright © 2011-2022 走看看