Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Fahman Khan
3,798 PointsPolymorphism
public class MyClass { private Object o;
public void setObject(Object s) { this.o=s; } }
In my main class, suppose i did this
MyClass hi=new MyClass(); hi.setObject(new String("hello"));
Question: When i pass in a string to my setObject method, what gets stored in this.o? Does the string object gets casts to the Object?
1 Answer
Grigorij Schleifer
10,365 PointsInteresting .... but your setObject method take an Object as a parameter, why do you pass a String in the setObejct method???
Iain Diamond
29,379 PointsIain Diamond
29,379 PointsFahman Khan said:
In my main class, suppose i did this
Reply:
When you instantiate class Myclass, variable o, is created as a reference (or pointer) to an Object type, which can point at any kind of Java object. This can be passed into any method that takes an Object argument.
In your example, when you call the setter function setObject you're passing in a String object, which has allocated memory on the heap. Within the class you'll have an Object reference, o, that points at a String object.
So in short, the String, "hello", has been type converted to Object type.
If you need to, you could change the class variable type back to String as the real object in memory remains a String object.