• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object reference contructor  RSS feed

 
dave hopkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps somebody could explain the following code to me:



There is no constructor for Object that takes a string as a parameter, so it must be using the Foo constructor. But how can this be, when you are not allowed to use any other Foo methods?

thanks.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no constructor for Object that takes a string as a parameter, so it must be using the Foo constructor.


The statement is even stricter. Constructors are not inherited. If you create a Foo object, you must use the Foo constructors.

But how can this be, when you are not allowed to use any other Foo methods?


You are allowed to use Foo's method, if the object is a Foo object. Unfortunately, the compiler does not know that -- you need to cast the object first.

Henry
 
dave hopkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand now thanks!
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has compile-time type checking. That is, you have to declare what class of object each reference points to, and you can only (directly[*]) call methods applicable to that class.

This is different to some other languages that only have run-time type checking. In Python or JavaScript, for instance, you do not declare what type a variable has. Each method call is only checked at run-time, and succeeds or fails according to the run-time type of the object on which it is called.

In Java, you can use casting to change the compile-time class of an object reference; it generally only makes sense to cast to a subclass of the object reference's current class. You can change an FooSuper object reference to a Foo object reference by casting. When you cast, you are saying to the compiler that you know what class of object is really pointed to by the object reference. A check occurs at run-time and throws ClassCastException if what you said isn't true.

Casting does not do anything to the actual object. You cannot change a Foo object to a Bar object by casting. Actually, you cannot change an object's class at all.

[*] Java Reflection includes another way to call Java methods, which bypasses most compile-time checks and leaves everything to run-time. It has many uses, but should not be used when simple non-reflection code would do, because (a) reflection code is long-winded, (b) the compile-time checks help to find bugs.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!