What is the difference between simple name, canonical name and class name in a Java class?

Java 8Object Oriented ProgrammingProgramming

Canonical name of a Java class is the name of the class along with the package. For example, the canonical name of the class File is java.io.File.

You can also get the canonical name of a particular class using Java method. The class named Class provides a method getCanonicalName(), this method returns canonical name of the current class.

Example

Live Demo

import java.lang.*;
public class ClassDemo {
   public static void main(String[] args) {
      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();
      
      //Returns the canonical name of the underlying class if it exists
      System.out.println("Class = " + cls.getCanonicalName());
   }
}

Output

Class = com.tutorialspoint.ClassDemo
raja
Published on 05-Jan-2018 16:09:51
Advertisements