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

}

}

结果;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会依据方法调用顺序依次查找有关的错误处理程序。

可使用printStackTracegetMessage方法了解异常发生的情况:

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

转载于:https://www.cnblogs.com/1336303471-tengxianliang/p/4960447.html

java动手动脑 6相关推荐

  1. java 动手动脑

    动手动脑1 1.以下代码为何无法通过编译?哪儿出错了? 答:如果类提供了一个自定义的构造方法,将导致系统不再提供默认构造方法. 2.请运行TestStaticInitializeBlock.java示 ...

  2. java动手动脑之多态

    1.java的语法特性: 1 public class ParentChildTest { 2 public static void main(String[] args) { 3 Parent pa ...

  3. java 动手动脑之父子继承

    1.构造函数的主要作用是什么? 作用:在创建对象时初始化对象,为对象成员变量赋初值. 调用时:子类-->父类-->祖类 输出时:祖类-->父类-->子类 在子类调用构造函数时必 ...

  4. JAVA课上动手动脑问题以及课后测试1,2总结

    课堂测试1      像二柱子那样,花二十分钟写一个能自动生成30道小学四则运算题目的 "软件" 2    (1)题目避免重复 (2)可定制(数量/打印方式) 设计思路 1)产生两 ...

  5. JAVA语法基础 动手动脑及课后作业

    动手动脑1: 仔细阅读示例: EnumTest.java,运行它,分析运行结果? public class EnumTest { public static void main(String[] ar ...

  6. 动手动脑-Java重载

    有以下例子: 例: Using overloaded methods public class MethodOverload { public static void main(String[] ar ...

  7. Java之动手动脑(三)

    日期:2018.10.12 星期五 博客期:017 这次留了两个动手动脑作业!我需要一个一个来说!先说第一个吧! Part 1 :随机生成1000个随机数 代码: 1 //以下为 RandomMake ...

  8. java part.inlimen_java字符串加密及动手动脑

    字串加密: 请编写一个程序,使用上述算法加密或解密用户输入的英文字串要求设计思想.程序流程图.源代码.结果截图. 设计思想:先输入一个字符串,调用toCharArray()函数将它转化为字符数组,在利 ...

  9. JAVA语法基础作业——动手动脑以及课后实验性问题(一)

    一.枚举类型 public class EnumTest {  public static void main(String[] args) {    Size s=Size.SMALL;    Si ...

最新文章

  1. Codeforces Round #653 (Div. 3)部分题解
  2. python sum 数组原理_Python - Sum 4D数组
  3. 剑指offer 树的子结构
  4. 512M内存编译php出错
  5. 一步一步学Remoting系列文章
  6. 30-Python3 正则表达式
  7. loj 6085.「美团 CodeM 资格赛」优惠券
  8. python基于base64模块实现图像数据编码处理、解码还原实践【解决解码数据损失问题】
  9. 怎么用python扫描主机_python 扫描内网存活主机
  10. 联想台式电脑序列号查看方法
  11. java web后台生成随机数字字母验证码
  12. 哈希算法----猜词游戏
  13. 支付宝支付--手机支付
  14. Vue脚手架运行报错-4058
  15. JS使用技巧-如何解决谷歌浏览器下载图片、PDF文档时只打开不下载的问题?
  16. 如何使用Foobar2000将音乐文件按照专辑或者歌手名分出文件夹
  17. 分数指数幂计算机,分数指数幂的教案
  18. 文档布局分析工具之DIVA
  19. 《Internet 路由结构(第2版•修订版)》一7.6 参考资料
  20. 618商战大片谢幕,销量冠军竟然有两个?

热门文章

  1. PYTORCH批标准化
  2. 用Java设计一个通讯录,保存读者的信息。
  3. linux yum imagemagick,CentOS7安装 ImageMagick
  4. php cookie注销,注销后未设置php cookie
  5. 基于深度学习检测驾驶员的走神行为
  6. window ftp open命令打不开_Centos7上搭建ftp
  7. python 判断类是否有某个属性_python判断对象某个属性的方法有哪些
  8. 安装navicat之后双击就会闪退_win2012,2016 能安装oracle 10g吗?
  9. android的CursorLoader用法小结
  10. 十八年开发经验分享(一)学习篇