-1

I am so much confused for the following declaration of the object in Java. for ex: I need to create a object for the ClassName

I can do it in two ways:

  1. Object obj = new ClassName();
  2. ClassName obj1 = new ClassName();

what is the primary difference between this obj and obj1 or they are the same?

Uraz Pokharel
  • 210
  • 1
  • 13
  • 2
    The objects are instances of the same type, but the variables have a different compile-time type... – Jon Skeet Dec 02 '15 at 17:58
  • Read about dynamic polymorphysm – Rahman Dec 02 '15 at 17:59
  • Possible duplicate of [What is the difference between dynamic and static polymorphism in Java?](http://stackoverflow.com/questions/20783266/what-is-the-difference-between-dynamic-and-static-polymorphism-in-java) – Basilevs Dec 02 '15 at 18:01
  • Almost exact duplicate too: [awkwardness in creating object](http://stackoverflow.com/q/31327896) – Basilevs Dec 02 '15 at 18:02

3 Answers3

2

Object is a superclass of ClassName, in fact, it's the top-most class of all classes you create. Java allows you to use a subclass as if it were an instance of a superclass (it has the same methods, although they might be overriden).

The difference lies in how you can use them. In the first case, the compiler will see obj as a reference of type Object and the reference actually points to an instance of type ClassName. In your second case, your compiler will see obj1 as a reference of type ClassName and the reference points to an instance of type ClassName.

In the first case, you won't be able to call any methods declared in the subclass, since the type Object doesn't actually contain these methods (and the compiler won't know about them), whereas you can use the second way to call methods and access fields declared in the subclass.

Shadowwolf
  • 973
  • 5
  • 13
1

Object obj = new ClassName(); your creating a reference obj of type Object and making it refer to a ClassName instance .

ClassName obj1 = new ClassName(); , here both the object created and reference are of type ClassName.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

I recommend reading about the concept of (dynamic) polymorphism in the official Java tutorial by Oracle.

Link is right here.

matt-pielat
  • 1,659
  • 3
  • 20
  • 33