faisal abdulai
faisal abdulai

Reputation: 3819

java class initialization explanation

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
} 

Upvotes: 0

Views: 122

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

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

Upvotes: 0

gelu
gelu

Reputation: 65

  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".

Upvotes: 0

Keith Randall
Keith Randall

Reputation: 23265

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.

Upvotes: 4

Related Questions