码迷,mamicode.com
首页 > 其他好文 > 详细

多态与异常处理

时间:2015-11-15 21:53:19      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

TestInstanceof验证:

public class TestInstanceof

{

public static void main(String[] args) 

{

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

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

Object hello = "Hello";

//StringObject类的子类,所以返回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));

}

}

技术分享

 

TestCast的验证:

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;

 

}

}

技术分享

 

多态的最基本的特征就是父类变量可以引用子类变量对象。Parent p=new child();

总是可以让更一般的对象容纳更具体化的对象。子类对象可以直接赋值给基类对象。基类对象要赋值给子类对象,必须执行类型转换。语法结构是:子类对象变量=(子类名)基类对象名;也不能乱转换,如果类型转换失败java会抛出以下这种异常:ClassCastException

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

}

}

 

 

子类和父类拥有一样的方法,并且让父类引用子类对象时,调用哪个方法是由对象自己的真实类型决定的,对象是子类型的就调用子类的方法,是父类的,就调用父类的方法。子类有与父类相同的字段,子类中的字段会代替或隐藏父类中的字段,子类方法访问的是子类的字段,如果子类想访问父类被隐藏的字段可以用super调用。如果子类被当做父类使用时,则子类访问的字段是父类的。

技术分享

异常处理

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

     }

 

  }

}

技术分享

 

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

        } 

    } 

}

技术分享

 

 

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

        } 

    } 

}

技术分享

 

 

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

        

}

    

}

 

}

技术分享

 

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

        }

 

   }

 

 

}

技术分享

 

// 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() + "\n" );

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

   }

}

技术分享

 

 

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

    } 

}

技术分享

 

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

{

            //...

}

}

 

/**

 * 自定义的异常类

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

   }

}

技术分享

 

多态与异常处理

标签:

原文地址:http://www.cnblogs.com/11-05/p/4967460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!