Home » Java programming language

Java Class class asSubclass() method with example

Class class asSubclass() method: Here, we are going to learn about the asSubclass() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 04, 2019

Class class asSubclass() method

  • asSubclass() method is available in java.lang package.
  • asSubclass() method casts this Class object to denote a subclass of the class denoted by the given Class object.
  • asSubclass() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • asSubclass() method may throw ClassCastException at the time of casting a Class.
    ClassCastException: In this exception when this Class does not denote a subclass of the given class.

Syntax:

    public Class asSubclass(Class class_name);

Parameter(s):

  • Class class_name – represents the name of the class.

Return value:

The return type of this method is Class, it returns this Class object, cast to denote a subclass of the given Class object.

Example:

// Java program to demonstrate the example 
// of Class asSubclass (Class class_name) method of Class class

public class ParentClass {
    public static void main(String[] args) throws Exception {
        // Creating ParentClass and ChildClass instance
        ParentClass pc = new ParentClass();
        ParentClass cc = new ChildClass();

        // Get Classname
        Class parent = pc.getClass();
        System.out.println("Parent Class: " + parent);

        Class child = cc.getClass();
        System.out.println("Child Class: " + child);

        // We are denoting ChildClass of the given ParentClass object
        Class subclass = child.asSubclass(parent);
        System.out.println("child.asSubclass(parent): " + subclass);
    }
}

class ChildClass extends ParentClass {

}

Output

Parent Class: class ParentClass
Child Class: class ChildClass
child.asSubclass(parent): class ChildClass


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.