Say suppose I have the following Java code.
public class Example {
public static void main(String[] args){
Person person = new Employee();
}
}
How to find out whether the Person is a class or an interface?
Because the Employee
class can extend it if it's a class, or implement it if it's an interface.
And in both cases Person person = new Employee(); is valid.
Differences between a Class and an Interface:A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types.
You can use isInterface() method of java. lang. Class to check whether a class is an interface or not.
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction.
If you don't already know whether Person
is an interface or a class by nature of the documentation for the class/interface itself (you're using it, presumably you have some docs or something?), you can tell with code:
if (Person.class.isInterface()) {
// It's an interface
}
Details here.
Edit: Based on your comment, here's an off-the-cuff utility you can use:
public class CheckThingy
{
public static final void main(String[] params)
{
String name;
Class c;
if (params.length < 1)
{
System.out.println("Please give a class/interface name");
System.exit(1);
}
name = params[0];
try
{
c = Class.forName(name);
System.out.println(name + " is " + (c.isInterface() ? "an interface." : "a class."));
}
catch (ClassNotFoundException e)
{
System.out.println(name + " not found in the classpath.");
}
System.exit(0);
}
}
Usage:
java CheckThingy Person
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With