继承类

 1 public class TestInstanceof
 2 {
 3     public static void main(String[] args) 
 4     {
 5         //声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
 6         //但hello变量的实际类型是String
 7         Object hello = "Hello";
 8         //String是Object类的子类,所以返回true。
 9         System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
10         //返回true。
11         System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
12         //返回false。
13         System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));
14         //String实现了Comparable接口,所以返回true。
15         System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));
16         String a = "Hello";
17         //String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
18         //System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
19     }
20 }

运行结果:

字符串是否是Object类的实例:true
字符串是否是String类的实例:true
字符串是否是Math类的实例:false
字符串是否是Comparable接口的实例:true

与字符串实例有有关的类是Object类,它是String类的父类;String类,字符串的类型;Comparable类,String类实现了Comparable类,所有字符串是Comparable的示例。

 1 class Mammal{} //父类
 2 class Dog extends Mammal {} //子类
 3 class Cat extends Mammal{} //子类  java继承为单继承
 4 
 5 public class TestCast
 6 {
 7     public static void main(String args[])
 8     {
 9         Mammal m;
10         Dog d=new Dog();
11         Cat c=new Cat();
12         m=d;
13         //d=m;   //报错无法运行
14         d=(Dog)m;
15         //d=c; //报错无法运行
16         c=(Cat)m;
17 
18     }
19 }

以上代码说明:

类的示例可以将父类的实例化赋值给子类,反之则不能,说明只能由大到小,不能由小到大的赋值。

 1 class Parent{
 2     public int myValue=100;
 3     public void printValue() {
 4         System.out.println("Parent.printValue(),myValue="+myValue);
 5     }
 6 }
 7 class Child extends Parent{
 8     public int myValue=200;
 9     public void printValue() {
10         System.out.println("Child.printValue(),myValue="+myValue);
11     }
12 }
13 
14 public class ParentChildTest {
15     public static void main(String[] args) {
16         Parent parent=new Parent();
17         parent.printValue();
18         Child child=new Child();
19         child.printValue();
20         
21         parent=child;
22         parent.printValue();
23         
24         parent.myValue++;
25         parent.printValue();
26         
27         ((Child)parent).myValue++;
28         parent.printValue();
29         
30     }
31 }

运行结果:

Parent.printValue(),myValue=100
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=201

说明:

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

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

原文地址:https://www.cnblogs.com/cxy0210/p/11728964.html