This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is this legal?  RSS feed

 
Keith Rainey
Ranch Hand
Posts: 66
Android Eclipse IDE IntelliJ IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it possible to create an object of type Class within the class definition? This seems very chicken vs. egg to me....


public class Why
{
public static void main(String[] args)
{
Why myWhy= new Why();
}
}
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66205
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rather than asking why you can, why shouldn't it be?
 
Keith Rainey
Ranch Hand
Posts: 66
Android Eclipse IDE IntelliJ IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Classes are typically presented as 'blueprints' for objects. Following the analogy, it doesn't make sense to me to be able to create the object from an incomplete blueprint. It seems like a circular reference to me.
This obviously is a conceptual failure on my part as the code compiles and runs.
 
Jared White
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this discussion it is important to remember the difference between a Class and an Object.
The class is static and always exists.

To get an object it must be created with the new statement.

The Class and Object are 2 different entities.
Think of the Class as a blueprint or plans to create something and the object that something that is created.

The Class is neither the chicken nor the the egg. The class is the creator, or what is used to create.

I hope this helps.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is legal in other object orient languages as well -- in fact, I can't think of one OO language where this isn't allowed.

Henry
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66205
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keith Rainey wrote:it doesn't make sense to me to be able to create the object from an incomplete blueprint.

Why is it incomplete? The code, including the new operator, isn't executed at compile time, but at run time. The class definition exists long before the code within it ever gets a chance to run.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!