• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Referencing an Object's Variables

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I'm brand new to java and the community.I was just kick starting with the sun's java tutorial and stuck up at Object's and classes fundamentals even though i've done c++(No projects or experience, just amateur).I'm pasting the text from the tutorial as it is:
:::::::::::::::::::
Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object's variables:
height = new Rectangle().height;
This statement creates a new Rectangle object and immediately gets its height. Effectively, the statement calculates the default height of a Rectangle.
:::::::::::::::::::
where a rectangle class is already defined.Now as no variable holds the object value, is .height a class variable?
Consider this :
' creates a new Rectangle object and immediately gets its height '
Is this value of height defined in some costructor?


I'm eagerly waiting for your replies.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, you are right. When you do this:
<PRE>
int height;
height = new Rectangle().height;
</PRE>
you are creating a new instance of the Rectangle class but you haven't given it a name, so you won't be able to access it later. In this case, height will get whatever value Rectangle's constructor assigns to its height member variable.
You probably would not really do this in code. They are just showing you how you can access the member variables of an object you have just created without using multiple statements. It's a good trick to know, but you probably wouldn't use it in the way they have used it.
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic