Why we have to use class in java

What does .class mean in Java?

What does .class mean in Java? For example, if I created a class called Print . What does Print.class return?

This certainly looks like a real question to me. I was just asking this question myself, and found myself here after a quick Google search. I guess I shouldn’t have bothered if I’d known that my question wasn’t real!

Also, I think because of the awkwardness of the particular search string, there is little written or findable about this question. Other than the API docs linked to above, I’ve never seen this notation mentioned anywhere else (although you often see it used in reflection).

@MadProgrammer the OP is asking about the .class syntax which is only incidentally related to the .class filename extension.

8 Answers 8

When you write .class after a class name, it references the class literal — java.lang.Class object that represents information about a given class.

For example, if your class is Print , then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print .

Print myPrint = new Print(); System.out.println(Print.class.getName()); System.out.println(myPrint.getClass().getName()); 

And how does Android handle new Intent(this, Activity.class ? Will it try to find out class Activity by comparing each class?

Читайте также:  Узнать все делители числа python

.class is used when there isn’t an instance of the class available.

.getClass() is used when there is an instance of the class available.

object.getClass() returns the class of the given object.

String string = "hello"; System.out.println(string.getClass().toString()); 

This is the class of the string object 🙂

getClass() is only useful if you have a reference pointing to an object of the class. ClassName.class can be used even if the class has no instances. For example, consider Math.class . Each is correct for certain situations.

Brilliant explanation. Right to the point of it.Love how you identified the distinction between .class and .getClass().

Just to clarify, this ‘.class’ method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.

This ‘.class’ method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.

Normally you don’t plan on using Reflection right away when you start building your project. It’s something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular ‘clone’ to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()

If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct 

If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.

 package test; public class Test < public static void main(String[] args) < //there is no instance available for class Test, so use Test.class System.out.println("Test.class.getName() . " + Test.class.getName()); // Now create an instance of class Test use getClass() Test testObj = new Test(); System.out.println("testObj.getClass().getName() . " + testObj.getClass().getName()); //For primitive type System.out.println("boolean.class.getName() . " + boolean.class.getName()); System.out.println("int.class.getName() . " + int.class.getName()); System.out.println("char.class.getName() . " + char.class.getName()); System.out.println("long.class.getName() . " + long.class.getName()); >> 

I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.

Adding to the above answers:

Suppose you have a a class named «myPackage.MyClass». Assuming that is in classpath, the following statements are equivalent.

//checking class name using string comparison, only Runtime check possible if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName())<> //checking actual Class object for equality, only Runtime check possible if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass")))<> //checking actual Class object for equality, but compile time validation //will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm) if(myInstance.getClass() == MyClass.class)<> 

Similarly, the following are also equivalent.

Class myClassObject = MyClass.class; //compile time check Class myClassObject = Class.forname("myPackage.MyClass"); //only runtime check 

If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package. MyClass.class is a shorthand method which actually points to the Class object representing MyClass.

As an addendum, some information about Class reference which will be useful to read along with this as most of the time, they are used together.

Class reference type can hold any Class object which represents any type.

This works in a similar fashion if the Class reference is in method argument as well.

Please note that the class «Class» does not have a public constructor. So you cannot instantiate «Class» instances with «new» operator.

Источник

Java why do we use class in java

Sometimes we can declare a class inside another class such types of classes is called inner classes. We can declare an inner class with the static modifier, such types of inner classes are called static nested classes.

Different Types of Classes in Java with Examples

A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:

  • Modifiers: A class can be public or has default access
  • class keyword: class keyword is used to create a class.
  • Class name: The name should begin with an initial letter (capitalized by convention).
  • Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  • Body: The class body surrounded by braces, < >.

We can define class members and functions inside the class. Different types of classes:

1. Static Class

We can declare a class as static if and only if it is a nested class. We can declare an inner class with the static modifier, such types of inner classes are called static nested classes. In the case of normal or regular class without the existing outer class object, there is no chance of existing inner class object i.e inner class object is strongly associated with an outer class object. In the case of static nested classes, there may be a chance of declaring the nested class object without an outer class object.

Note :

If we want to declare a nested class object from outside of the outer class then we can create as follows

Syntax:

Outerclassname.innerclassname objectvariable= new Outerclassname.innerclass name();

Example:

Test.Nested n= new Test.Nested();

Hence it is said that there may be a chance of existing nested class objects without existing outer class objects. In normal or regular inner classes we can’t declare any static members, but in static nested classes we can declare static members including the main method, so, we can invoke static nested class directly from the command prompt.

Properties of the static class:

  1. static class objects cannot be created.
  2. static class can only have static members.
  3. static class cannot access members (non-static) of the outer class.

Источник

What is class in Java

Java is a multi-purpose, client-side programming language that follows the concept of object-oriented programming(OOP). If we talk about the OOP, it has some fundamental concepts such as classes, objects, inheritance, polymorphism, etc. Among them, one of the most significant concepts is classes. Creating a class in Java is as good as creating a data type. A Java class can have multiple class attributes, member functions, constructors, and nested classes.

This post will provide a profound understanding of the below-listed concepts:

Before heading towards the java classes first we have to understand what is the need for a java class or why someone should use a java class. So, let’s begin!

What is a Java Class

It is a description of an object’s properties and actions. Let’s assume we have to construct a building and to do so, we require a plan(blueprint). Here, the blueprint or plan represents a class while the building is an object. So, all in all, we can say that the class defines the state and behavior of an object.

Why Java Class?

Java provides primitive data types such as int, float, double, etc. Using these data types we can create variables. The primitive data types are useful when we have to store a single value in a variable such as a person’s age, name, etc.

But what if we have to store a set of information e.g. we need to store the information about an employee such as his name, age, id, department, salary, etc. We can’t store all this information in one variable.

We need multiple variables of various data types to store the employee data. But in such a case, it wouldn’t be possible to maintain the relationship of these variables (i.e.we need to group all the variables to store the data of a single student which is not possible using primitive data types).

Therefore, to deal with such situations, OOP offers the concept of classes. The class allows us to group all these variables in a single template.

How to Create a Java Class

The below code snippet will provide you with all the necessary details to understand how to create a java class:

A Java class can have class attributes/variables, constructors, blocks, methods, and nested classes.

How to Access Class Members in Java

To access any member of the java class, we have to create and utilize the object of that class. The snippet given below will assist you in this regard:

In this way, we can create the object of some specific class using a “new” keyword. Now, consider the below snippet to understand how to access any class member in java:

Using dot “.” syntax we can access any class member.

Practical Implementation of a Java Class

Let’s consider the example given below to understand the working of a Java Class.

Example

In the below-given snippet, we will create a class “EmployeeExample” that contains three class attributes: empName, empAge, and empId. Moreover, we will create a method to show the employee details “displayData()”:

publicclassEmployeeExample {
String empName = «Joe» ;
intempId = 13 ;
intempAge = 27 ;
voiddisplayDetails ( ) {
System . out . println ( «Employee Name: » + empName ) ;
System . out . println ( «Employee Age: » + empAge ) ;
System . out . println ( «Employee Id: » + empId ) ;
}
publicstaticvoidmain ( String [ ] args ) {
EmployeeExample emp = newEmployeeExample ( ) ;
System . out . println ( «Employee Name: » + emp. empName ) ;
emp. displayDetails ( ) ;
}
}

In the main method, first, we created the object of the class, and afterward, we accessed the class attributes and class method using that object:

The above snippet verified the working of the Java class.

Conclusion

A java class is a blueprint that provides the description of an object’s properties and behavior. In java “class” keyword is used to create a class. A Java class can have class attributes/variables, constructors, blocks, methods, and nested classes. The class members can be accessed using the object of that class (i.e. classObject.classMember;). This post explained various aspects of java class such as how to create a java class, how to access the class members, etc.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

Оцените статью