Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with the class keyword in Java

Tags:

java

class

I don't really understand how the class keywords work in some instances.

For example, the get(ClientResponse.class) method takes the ClientResponse.class. How does it use this when it gets it, and what are the advantages over just passing an instance of it?

like image 369
Mario Dennis Avatar asked Oct 19 '12 21:10

Mario Dennis


People also ask

What is a class keyword in Java?

The class keyword is used to declare a new Java class, which is a collection of related variables and/or methods. Classes are the basic building blocks of object−oriented programming. A class typically represents some real−world entity such as a geometric Shape or a Person.

Can we use keyword as class name in Java?

In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a variable nor the name of a folder used for package.

How This keyword works in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

How do classes work together in Java?

Typically, Java programs that you write will create many different objects from templates known as classes. These objects interact with one another by sending each other messages. The result of a message is a method invocation which performs some action or modifies the state of the receiving object.


1 Answers

In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.

The keyword is the one that we use to define a class in Java. e.g.

public class MyClass { } /* class used here is one of the keywords in Java */

The class in ClientResponse.class is a short-cut to the instance of Class<T> that represents the class ClientResponse.

There is another way to get to that instance for which you need an instance of ClientResponse. e.g

ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass(); 

what are the advantage over just passing a instance of it?

In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.

like image 182
Bhesh Gurung Avatar answered Sep 29 '22 12:09

Bhesh Gurung