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

第七章课堂例子

时间:2015-11-16 00:51:46      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:

一、使用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));
}
}

   技术分享

二、类型转换

 技术分享

子类可直接赋给基类(“基类变量=子类对象”);

基类的引用类型要传递给子类必须通过强制转换(“子类变量=(子类名)基类对象”);

子类之间不可以进行转换。

 

技术分享

三、变态类


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关键字来访问它。 如果子类被当作父类使用,则通

     过子类访问的字段是父类的。

四、

package test;


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

}

技术分享

   JVM是java虚拟机,finally是由JVM保证执行,而System.exit(0)是正常退出程序,结束JVM的运行,那么最后finally就不再执行。

PS:System.exit(status)不管status为何值都会退出程序,非0,则表示为非正常退出程序,一般放在catch块中,当捕获到异常,需要

停止程序,用非0值来表示非正常退出程序

第七章课堂例子

标签:

原文地址:http://www.cnblogs.com/DHYgg/p/4967804.html

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