java.lang.Class.getSuperclass()方法範例


java.lang.Class.getSuperclass() 返回類表示此Class所表示的實體(類,介面,基本型別或void)的超類。

宣告

以下是java.lang.Class.getSuperclass()方法的宣告

public Class<? super T> getSuperclass()

引數

  • NA

返回值

此方法返回當前物件所表示的類的超類。

異常

  • NA

例子

下面的例子顯示java.lang.Class.getSuperclass()方法的使用。

package com.yiibai;

import java.lang.*;

class superClass {
   // super class
}

class subClass extends superClass {
   // sub class
}

public class ClassDemo {

   public static void main(String args[]) {

     superClass val1 = new superClass();
     subClass val2 = new subClass();
     Class cls;

     cls = val1.getClass(); 
     System.out.println("val1 is object of type = " + cls.getName());

     /* returns the superclass of the class(superClass) represented 
     by this object */
     cls = cls.getSuperclass();
     System.out.println("super class of val1 = " + cls.getName());

     cls = val2.getClass(); 
     System.out.println("val2 is object of type = " + cls.getName());
     
     /* returns the superclass of the class(subClass) represented
     by this object */
     cls = cls.getSuperclass();
     System.out.println("super class of val2 = " + cls.getName());
   }
}

讓我們來編譯和執行上面的程式,這將產生以下結果:

val1 is object of type = superClass
super class of val1 = java.lang.Object
val2 is object of type = subClass
super class of val2 = superClass