0

I kind of new to java and will be happy if anybody could explain the following code samples to me.This is just a sample java code snippet for illustration. But the main question is that if the class Learn initializes another class Smart with a parameter which is also a class Object , then the addition of the dot class to the class Object Sample is kind of confusing to me. Any explanation will be appreciated. I apologize if it is a basic question. thanks.

class Learn {
//some codes 
Smart smart = new Smart(Sample.class);
//some codes
} 

3 Answers 3

4

Sample is the name of a class. It is not an object. A new Sample() is an object whose class is Sample. Sample.class is an object whose class is java.lang.Class which describes the class Sample.

Sign up to request clarification or add additional context in comments.

2 Comments

Straightforward explanation without too much blabla. +1
thanks for the correction , but then if i may ask further how different is Sample.class from an initialization like Sample sample = new Sample()
0
  1. In java, there is a class called "Class" that represent classes and interfaces.
  2. There are several ways to get an instance of class "Class". Please take a look at java.lang.Class document.
    • Class.forName(String className)
    • obj.getClass() -obj is any class instance
    • Sample.class -Sample is a class
  3. You are using the 3rd method to get an instance of class "Sample".

Comments

0

I will break your example in the following way....

Learn - is a Class

smart - is an Object Reference Variable of type Smart, we can say that Class Learn has a reference of type Smart.

Sample.class - Is a way of getting the Class<T> for a particular type.

Extract from Java Docs.

During implementation it depends on the Targeting bytecode version. If -target 1.4 (or below), a call to Class.forName() is inserted into your code in a static method which is called during type initialization. If you use -target 1.5 (or above) the constant pool gets a "class" entry

Please refer section 15.8.2 of the Java Language Specification for more details

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.