zoukankan      html  css  js  c++  java
  • java动手动脑 6

    1.可以使用instanceof运算符判断一个对象是否可以转换为指定的类型。

    public class TestInstanceof

    {

    public static void main(String[] args) 

    {

    //声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类

    //但hello变量的实际类型是String

    Object hello = "Hello";

    //String是Object类的子类,所以返回true。

    System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));

    //返回true。

    System.out.println("字符串是否是String类的实例:" + (hello instanceof String));

    //返回false。

    System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));

    //String实现了Comparable接口,所以返回true。

    System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));

    String a = "Hello";

    //String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过

    //System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));

    }

    }

     截图;

    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;

    }

    }

    截图;

    显示类型转换异常,因为DogCat之间不是继承关系,所以,无法将Dog对象想换换成为Cat对象。 

    3.运行课件中的例题ParentChildTest.java,回答下列问题:

    a) 左边的程序运行结果是什么?

    b) 你如何解释会得到这样的输出?

    c) 计算机是不会出错的,之所以得到这样的运行结果也是有原因的,那么从这些运行结果中,你能总结出Java的哪些语法特性?

    并修改 ParentChildTest.java,验证你的回答结果

    a ) 在左边的程序中public class ParentChildTest {

    /**

     * @param args

     */

    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();

    }

    }

    a) 运行结果;Parent.printValue(),myValue=100

              Child.printValue(),myValue=200

              Child.printValue(),myValue=200

              Child.printValue(),myValue=200

              Child.printValue(),myValue=201

    b) 第一和第二中父类和子类都分配了空间,调用父类和子类的构造方法,分别输出他们的值;第三个父类等于子类,当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象,由于对象是子类,父类调用的是子类的方法,输出子类的值;第四个parent.myValue++是对父类中的变量进行自加运算,而parent.printValue()实际上调用的还是子类的构造方法;第五个((Child)parent).myValue++是将parent对象强制转化成Child,所以指向的是Child类中的变量,进行自加运算之后输出。

    c )  当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

         这个特性实际上就是面向对象“多态”特性的具体表现。

         如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

         如果子类被当作父类使用,则通过子类访问的字段是父类的!

    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();

    ((Child)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);

    }

    }

    截图;

    4.请阅读并运行AboutException.java示例,然后通过后面的几页PPT了解Java中实现异常处理的基础知识

    import javax.swing.*;

    class AboutException {

       public static void main(String[] a) 

       {

          int i=1, j=0, k;

          k=i/j;

    try

    {

    k = i/j;    // Causes division-by-zero exception

    //throw new Exception("Hello.Exception!");

    }

    catch ( ArithmeticException e)

    {

    System.out.println("被0除.  "+ e.getMessage());

    }

    catch (Exception e)

    {

    if (e instanceof ArithmeticException)

    System.out.println("被0除");

    else

    {  

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

    }

    }

    finally

         {

          JOptionPane.showConfirmDialog(null,"OK");

         }

      }

    }

    截图;

    使用Java异常处理机制

    (1)Java 中所有可捕获的异常都派生自 Exception 类。

    (2)把可能会发生错误的代码放进try语句块中。

    (3)当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误,catch语句块中的代码用于处理错误。

    (4)当异常发生时,程序控制流程由try语句块跳转到catch语句块。

    (5)不管是否有异常发生,finally语句块中的语句始终保证被执行。

    (6)如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

    Java中的异常分类;

    (7)Throwable类有两个直接子类:Exception:出现的问题是可以被捕获的;Error:系统错误,通常由JVM处理。

    (8)可捕获的异常又可以分为两类:check异常:直接派生自Exception的异常类,必须被捕获或再次声明抛出;runtime异常:派生自RuntimeException的异常类。使用throw语句可以随时抛出这种异常对象。

    (9)可以有多个catch语句块,每个代码块捕获一种异常。在某个try块后有两个不同的catch 块捕获两个相同类型的异常是语法错误。

    (10)使用catch语句,只能捕获Exception类及其子类的对象。因此,一个捕获Exception对象的catch语句块可以捕获所有“可捕获”的异常。

    (11)将catch(Exception e)放在别的catch块前面会使这些catch块都不执行,因此Java不会编译这个程序。

    finally”的功用:

    资源泄露:当一个资源不再被某应用程序使用,但此程序并未向系统声明不再使用此资源时发生这种情况

    finally语句块主要用于解决资源泄露问题,它位于catch语句块之后,JVM保证它们一定执行。

    注意:finally语句块中也可能发生异常,如果这种情况发生,先前的异常被放弃。

    5.阅读以下代码(CatchWho.java),写出程序运行结果:

    public class CatchWho { 

        public static void main(String[] args) { 

            try { 

                try { 

                    throw new ArrayIndexOutOfBoundsException(); 

                } 

                catch(ArrayIndexOutOfBoundsException 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"); 

            } 

        } 

    }

    运行结果;ArrayIndexOutOfBoundsException/内层try-catch

             发生ArithmeticException

    6.写出CatchWho2.java程序运行的结果;

    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"); 

            } 

        } 

    }

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

    7.请先阅读 EmbedFinally.java示例,再运行它,观察其输出并进行总结。

    public class EmbededFinally {

    public static void main(String args[])   

    int result;

    try {        

    System.out.println("in Level 1");       

      try {           

    System.out.println("in Level 2");

      // result=100/0;  //Level 2

      try {              

      System.out.println("in Level 3");

      result=100/0;  //Level 3

    }              

    catch (Exception e) {  

    System.out.println("Level 3:" + e.getClass().toString());              

    }                             

    finally {                 

    System.out.println("In Level 3 finally");              

    }                             

    // result=100/0;  //Level 2

    }            

    catch (Exception e) {

      System.out.println("Level 2:" + e.getClass().toString());        

      }

      finally {

    System.out.println("In Level 2 finally");

     }

    // result = 100 / 0;  //level 1

    }       

    catch (Exception e) {

    System.out.println("Level 1:" + e.getClass().toString());

    }      

    finally {

      System.out.println("In Level 1 finally");

    }

    }

    }

    输出;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时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

    8.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");

            }

        }

    }

    结果;in main

    Exception is thrown in main

    如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序

    9.请通过 PrintExpressionStack.java示例掌握上述内容。

    // UsingExceptions.java

    // Demonstrating the getMessage and printStackTrace

    // methods inherited into all exception classes.

    public class PrintExceptionStack {

       public static void main( String args[] )

       {

          try {

             method1();

          }

          catch ( Exception e ) {

             System.err.println( e.getMessage() + " " );

             e.printStackTrace();

          }

       }

       public static void method1() throws Exception

       {

          method2();

       }

       public static void method2() throws Exception

       {

          method3();

       }

       public static void method3() throws Exception

       {

          throw new Exception( "Exception thrown in method3" );

       }

    }

    结果;Exception thrown in method3

    java.lang.Exception: Exception thrown in method3

    at PrintExceptionStack.method3(PrintExceptionStack.java:28)

    at PrintExceptionStack.method2(PrintExceptionStack.java:23)

    at PrintExceptionStack.method1(PrintExceptionStack.java:18)

    at PrintExceptionStack.main(PrintExceptionStack.java:8)

    当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。

    可使用printStackTrace 和 getMessage方法了解异常发生的情况:

    printStackTrace:打印方法调用堆栈。

    每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。

    10.一个方法可以声明抛出多个异常

    import java.io.*;

    public class ThrowMultiExceptionsDemo { 

        public static void main(String[] args) 

         { 

          try { 

                throwsTest(); 

           } 

            catch(IOException e) { 

                System.out.println("捕捉异常"); 

            }

        }

        private static void throwsTest()  throws ArithmeticException,IOException { 

            System.out.println("这只是一个测试"); 

            // 程序处理过程假设发生异常

            throw new IOException(); 

            //throw new ArithmeticException(); 

        } 

    }

    结果;这只是一个测试

    捕捉异常

    11.OverrideThrows.java示例展示了Java子类的throws子句抛出的异常,不能是其基类同名方法抛出的异常对象的父类。

    import java.io.*;

    public class OverrideThrows

    {

    public void test()throws IOException

    {

    FileInputStream fis = new FileInputStream("a.txt");

    }

    }

    class Sub extends OverrideThrows

    {

    //如果test方法声明抛出了比父类方法更大的异常,比如Exception

        //则代码将无法编译……

    public void test() throws FileNotFoundException

    {

                //...

    }

    }

    结果;这只是一个测试

           捕捉异常

    12.ExceptionLinkInRealWorld.java示例展示了典型的异常处理代码模板

    /**

     * 自定义的异常类

     * @author JinXuLiang

     *

     */

    class MyException extends Exception

    {

        public MyException(String Message) {

            super(Message);

        }

        public MyException(String message, Throwable cause) {

            super(message, cause);

        }

         public MyException( Throwable cause) {

            super(cause);

        }

    }

    public class ExceptionLinkInRealWorld {

       public static void main( String args[] )

       {

          try {

             throwExceptionMethod();  //有可能抛出异常的方法调用

          }

          catch ( MyException e )

          {

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

             System.err.println(e.getCause().getMessage());

          }

          catch ( Exception e )

          {

             System.err.println( "Exception handled in main" );

          }

          doesNotThrowException(); //不抛出异常的方法调用

       }

       public static void throwExceptionMethod() throws MyException

       {

          try {

             System.out.println( "Method throwException" );

             throw new Exception("系统运行时引发的特定的异常");  // 产生了一个特定的异常

          }

          catch( Exception e )

          {

             System.err.println(

                "Exception handled in method throwException" );

             //转换为一个自定义异常,再抛出

             throw new MyException("在方法执行时出现异常",e);

          }

          finally {

             System.err.println(

                "Finally executed in throwException" );

          }

          // any code here would not be reached

       }

       public static void doesNotThrowException()

       {

          try {

             System.out.println( "Method doesNotThrowException" );

          }

          catch( Exception e )

          {

             System.err.println( e.toString() );

          }

          finally {

             System.err.println(

                "Finally executed in doesNotThrowException" );

          }

          System.out.println(

             "End of method doesNotThrowException" );

       }

    }

    结果;Method throwException

    Exception handled in method throwException

    Finally executed in throwExceptionMethod doesNotThrowException

    在方法执行时出现异常

    系统运行时引发的特定的异常

    Finally executed in doesNotThrowException

    End of method doesNotThrowException

  • 相关阅读:
    C#中 Thread,Task,Async/Await,IAsyncResult 的那些事儿!
    Java8的新特性以及与C#的比较
    点旋转坐标变换
    vc++返回模块路径
    为什么不要 "lock(this)" ? lock object 并是readonly(转载)
    《黄帝内经》要义
    C++多线程编程简单实例
    c++ 获取文件大小
    c# 获取文件夹大小
    自动驾驶仿真工具的下载与安装
  • 原文地址:https://www.cnblogs.com/1336303471-tengxianliang/p/4960447.html
Copyright © 2011-2022 走看看