Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game. |
| Notices |
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto |
Site FAQ |
Sitemap |
Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
 |
GNU/Linux Basic Guide
This 255-page guide will provide you with the keys to understand the philosophy of free software, teach you how to use and handle it, and give you the tools required to move easily in the world of GNU/Linux. Many users and administrators will be taking their first steps with this GNU/Linux Basic guide and it will show you how to approach and solve the problems you encounter.
Click Here to receive this Complete Guide absolutely free. |
|
 |
03-08-2006, 11:19 PM
|
#1
|
|
Member
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264
Rep:
|
JAVA: Reference Variables (Pointers) and Constructors
Hi,
I am taking Java as an elective. I have never had any java experience, so I am trying something new. I have some basic background in c++ and perl, as well as shell scripting and M$ ba(y)-sick.
In class, we started conquering objects and different methods. The professor keeps on referring to all of the explanations behind the syntaxes "walter cronkite" ("That's the way it is").
I started to read up on the topic, but i didn't get far, as for one, most sites about java with google return either nothing useful, or they simply show you how it works. I am trying to find out WHY it has to be the way it is.
When creating a new object, the syntax is as follows:
Code:
Class variable = new Class()
I understand the concept of variables. According to that, one is creating a variable of the type "Class", calling it "variable" and storing "new Class()" in it.
The "new Class" part is giving me a headache: i don't understand why one has to create a variable of the type "Class" and then store "Class" in it again. But that's just where the thought of train starts.
I am wondering:
- Is there a way to store other information in "Class variable", such "Class variable = new Class2()" or similar. If not, what's the point of writing the Class name 2x? wouldn't it then be enough to simple write "Class variable" to create a new object??
- What is the deal with the type of variable "Class"? What is going on behind the scenes when creating the variable?
- What is going on behind the screen when "new Class()" is running? What does the "new" and the constructor do?
- At what stage is something actually being written into memory?
It would be great if you knew a website which answeres these type of questions, or if you could actually take the time and explain it in your own words, that would be GREAT!
Thank You soooo much!
(I am not asking anybody to do my homework here. It is simply my interest in the topic, to which i have not found an answer yet. The textbook only describes the topic as "that's how you do it -- that's how it's done", whith little explanation and the attitude: "the way it is.")
Last edited by wwnexc; 03-08-2006 at 11:25 PM.
|
|
|
|
03-09-2006, 12:09 AM
|
#2
|
|
Guru
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,861
Rep: 
|
Hi -
I noticed your other post in the "first programming language" thread, and your observation about your college "Intro to Java Programming" course that a lot of students without any prior programming experience were dropping out - even though it was supposed to be an introductory course. I was going to ask "Do you think it's Java - or do you think maybe the problem is with the course?"
I think this post answered that question - it sounds like the instructor isn't doing a very good job of laying any kind of "background", to help you understand WHY things work the way they do.
ANYWAY:
1. As you probably know, in Java, "new" is an operator: just like "+" or "-". It "operates on" - does stuff" - to your program's data.
2. As you also know, in Java, there are a few "primitives" (like char, double and int) ...
and everything else is an "object".
3. The key point is that you have to *create* an object before it exists.
4. Another point is that, once the object exists, Java (unlike C++, for example),
*hides* quite a bit from you (like exactly *where* it exists, or who *else* might
be using that same object).
5. When you declare a variable (to some object or another), you're merely creating
a "reference". You presumably want to connect it to some real object or another.
6. That's where "new" comes in: it creates the *object*, which you can then get at using
your reference. For example:
Quote:
Code:
String s = new String ("asdf");
Not only does this mean "Make me a new String", but it also gives information about how to make the String by supplying an initial character string.
- from "Thinking in Java, 3rd Edition", Bruce Eckel
|
I'd very strongly encourage you to get a copy of "Thinking in Java" - it's an excellent book for the beginner; it's an equally good book for the experienced developer. I think you'll enjoy it.
It's also available on-line from Mr. Eckel's web site:
http://www.mindview.net
But personally, I prefer a book that I can thumb through, bookmark, write notes, etc.
Anyway - I hope that helps! And I sincerely hope things get to the point where you might get to *enjoy* your class (despite the "Walter Cronkite" factor ;-))
Last edited by paulsm4; 03-09-2006 at 12:12 AM.
|
|
|
|
03-09-2006, 12:11 AM
|
#3
|
|
Guru
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339
Rep:
|
Think this simple program for example:
Code:
public class MainClass () {
public MainClass() {
System.out.println("This is the constructor, you've just created a new MainClass Object");
}
public printMessage(String message) {
System.out.println(message);
}
public static void main(String[] arguments) {
MainClass someClass = new MainClass();
}
}
The line "MainClass someClass = new MainClass()" will create a new MainClass object. Your program starts at the public static void main and there you make a call to the constructor "public MainClass()" as soon as the "new" keyword is involked. Now, you can make calls to any public methods from the MainClass, for example:
Code:
public class MainClass {
public MainClass() {
System.out.println("This is the constructor, you've just created a new MainClass Object");
}
public void printMessage(String message) {
System.out.println(message);
}
public static void main(String[] args) {
MainClass someClass = new MainClass();
someClass.printMessage("Hello");
}
}
If you don't use new (thus only "MainClass someClass;") and try to call a method as we did with someClass.printMessage("Hello") you will get an error: "Variable someClass might not have been initialized".
Quote:
|
What is going on behind the screen when "new Class()" is running? What does the "new" and the constructor do?
|
Lot's of things. First, Java VM will allocate memory for the Object you are creating and then create the Object.
Quote:
|
- Is there a way to store other information in "Class variable", such "Class variable = new Class2()" or similar. If not, what's the point of writing the Class name 2x? wouldn't it then be enough to simple write "Class variable" to create a new object??
|
Absolutely. Think, for example, that you have two classes: class Car and class Saab. Saab is a subclass of Car(class Saab extends Car), you can then to this:
Car myCar = new Saab();
Since Saab is a car, it should work. However, the opposite would be wrong, because not every car is a Saab
Quote:
|
- At what stage is something actually being written into memory?
|
As soon as new is used, Java allocates memory for the Object you are creating.
Good luck!
EDIT: Correction made by spooon in the next post has been fixed in my message. Thank you spooon!
Last edited by Mega Man X; 03-10-2006 at 04:33 AM.
|
|
|
|
03-09-2006, 01:18 AM
|
#4
|
|
Senior Member
Registered: Aug 2005
Posts: 1,755
Rep:
|
Quote:
|
Originally Posted by Mega Man X
Saab myCar = new Car();
|
you mean
Car myCar = new Saab();
|
|
|
|
03-09-2006, 01:28 AM
|
#5
|
|
Member
Registered: Nov 2005
Location: India
Distribution: Fedora 11
Posts: 194
Rep:
|
looks like u might have already clarified ur doubts. iam replying just incase:-
in java memory has to be allocated explicitly. this helps the jvm to deallocate the memory after the program terminates. in c/c++, memory has to be deallocated manually.
hence, is java when u declare a variable u r only declaring it and not allocating memory for it.eg
class1 var;// u only declare it
var=new class1(); //with this u allocate memory. if u dont do this then u will get a NullPointerException during runtime.
when u derive a class then u can create a base class object using the derived class object.eg.
class derived extends baseClass
then this is possible,
derived obj=new baseClass();
|
|
|
|
03-09-2006, 02:40 AM
|
#6
|
|
Guru
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339
Rep:
|
Quote:
|
Originally Posted by spooon
you mean
Car myCar = new Saab();
|
Thank you 
|
|
|
|
03-09-2006, 03:28 AM
|
#7
|
|
Guru
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339
Rep:
|
I was bored, so I did a quick example based on the car thing. Try running it so you will see how it works. Let me know if something isn't quite clear
Code:
// Car.java
public abstract class Car {
protected int speed;
protected String model;
public Car() {
System.out.println("Super constructor");
}
public int getSpeed() {
return speed;
}
public String getModel() {
return model;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setModel(String model) {
this.model = model;
}
}
Code:
// Saab.java
public class Saab extends Car {
private int release_date;
/* Since Saab is a subclass to Car, the super()
* constructor will be called either you make it explictly
* or not. Trying to call another method before the super
* will return an error
*/
public Saab() {
//super() // -> the SuperClass constructor is called either you want or not
System.out.println("Saab constructor");
//super(); // <-- ERROR: The call for the super has to be the first argument in the constructor.
}
public void setReleaseDate(int release_date) {
this.release_date = release_date;
}
public int getReleaseDate() {
return release_date;
}
}
Code:
// MainClass.java
public class MainClass {
public static void main(String[] args) {
Car myCar = new Saab(); // <-- This is correct
myCar.setModel("Saab Sonnett");
System.out.println("My Car is a: " + myCar.getModel());
/*
* This won't work because the method
* setReleaseDate is not defined in the super
* class
*/
//myCar.setReleaseDate(1999); // <-- ERROR
Saab mySaab = new Saab();
mySaab.setReleaseDate(1999);
System.out.println("My Saab was released in: " + mySaab.getReleaseDate());
/*
* Java uses a simple inheritance method. Class Saab
* for example, could not extend two classes at
* once. If it's necessary to extend more then one class,
* we should use interfaces.(public class Saab extends Car implements <interface to implement>
* Since Saab is a subclass to Car, all methods and variables
* defined in the SuperClass are available for the subclass.
* Example:
*/
mySaab.setSpeed(20); // <-- This method is defined in the superclass, not in Saab
System.out.println(mySaab.getSpeed()); // <-- and this too, but available to the subclasses
/*
* This won't work because the SuperClass
* (Car) is declared as abstracted and
* can't be instantiated
*/
//Car myCar = new Car();
}
}
Last edited by Mega Man X; 03-10-2006 at 04:17 AM.
|
|
|
|
03-09-2006, 09:30 AM
|
#8
|
|
Member
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264
Original Poster
Rep:
|
Thank you for all your replies.
I think i start to understand the concept now. The example with the car and saab made things more obvious.
Mega Man X, Thank you for the nice example, with actual code. It really helped me understand the problem more than before.
So, if i understand things right, when you type: "int x;" you are only declaring memory for x, not actually writing anything into the memory yet.
I am really not trying so sound too dumb, but what exactly does the new command do? Does it actually create an object in memory, or does it only "free up" memory for it? What would be the best way to think of what it does?
About there being a problem with the class, I don't really think so. I am actually a high school student, who is taking a class at college next door. The class is basically all high school students, even thoug a few minutes before my class, a "real" college course with the same material, same professor, and same book finishes. Some of the people who dropped out, came in with this attitude: "Tell me how to make games! - I finally want to be able to make my own Battle Field 3". Now we are down to 4 (YES - four) students in the class.
|
|
|
|
03-09-2006, 09:44 AM
|
#9
|
|
Guru
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339
Rep:
|
You're welcome wwnexc. I'm glad it was of some help. Hey, I'm also willing to use Java to develop games. So far, I've a pong game
Anyway, if I understand correctly, when you declare int x(a primitive data type), Java allocates it on the "stack" (more about stack later). It won't allocate memory for it, just declare it. Java VM will _only_ allocate memory to Objects (created with the new operator). When you set an object to null (mySaab = null) the garbage collector is called and the memory mySaab was using is set free. You can make manual calls to the garbage collector with System.gc();
More techically speaking, on "stack", all variables and methods invocations are stored and on "heap", everything else is stored (like Objects). Heap is the actual memory(Free) available for usage.
Things stored on stack work in a LIFO (Last in, first out) fashion way.
I could not find anything clarifying better either Stack or Heap at Sun's homepage, but take a quick read here:
http://www.phptr.com/articles/articl...&seqNum=8&rl=1
Stack:
http://en.wikipedia.org/wiki/Stack_machine
Heap:
http://en.wikipedia.org/wiki/Heap_%28programming%29
Last edited by Mega Man X; 03-09-2006 at 09:52 AM.
|
|
|
|
03-09-2006, 12:59 PM
|
#10
|
|
Guru
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,861
Rep: 
|
Uh ... No. Not really.
1. The stuff about the stack and heap is almost right. The main idea really is:
Quote:
Things you allocate from the stack just exist for the lifetime of your
block or method. Things you allocate from the heap can have come into
existence before the procedure began, and can persist after the procedure ends
|
2. The key point about "new" is: that's the way you create objects.
3. Why the separation of simply "declaring an object" from explicitly saying "new"?
Several reasons:
4. On reason is that you might want to create the same type of object in any of several different ways. You just define different constructors (one for each different way the object can be created).
5. Or you might want to create a *specialized* "object instance" of a *general* "class type". The "Car" vs "Saab" thing is an excellent example.
Code:
EXAMPLE 1:
Car myCar = new Car(); // Create an object
Code:
EXAMPLE 2:
Car myCar = new Saab(); // Create a specialized object
Code:
EXAMPLE 3:
Car myCar = // Create an object with a non-default constructor
new Saab(new VehicleOptions ("red", "manual", "stabilizer"));
6. And of course another reason is that, once having *created* the object,
you might want make different *assignments*:
Code:
EXAMPLE 4:
Car myCar = new Saab();
Car herCar = new Hummer (new VehicleOptions ("yellow"));
Car anyCar = myCar;
anyCar.drive ();
anycar = herCar ();
anyCar.drive ();
Again, I'd strongly urge you to get a copy of Bruce Eckel's "Thinking in Java":
http://www.mindview.net/Books/TIJ/
PS:
In C++, you can allocate an object via an explicit "new", or directly on the stack. I won't bore you with any details or extraneous subtleties. In Java, the *only* way to get an object is with "new". Which *always* allocates from the heap.
Last edited by paulsm4; 03-09-2006 at 01:05 PM.
|
|
|
|
03-09-2006, 02:25 PM
|
#11
|
|
Guru
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339
Rep:
|
Excellent post paulsm4. I'm happy you liked the idea of Saab and Car too. When I was reading about Java and Polymorphism, the book I had was overly complicated (unless you are good at math) and made examples with trigonometric objects and formulas. I was lost, so I came up with something more... well... Mega Man X proof. Another analogy that works well is a Animal. Start with a Animal abstract class and build a Zoo-like all the way down the tree with Elephants, Giraffes, Bears and etc. Don't know, it's just easier for me to have things I can visualize
And about that book of yours, sounds awesome  . I will have to check it out!
Regards!
|
|
|
|
03-09-2006, 05:49 PM
|
#12
|
|
Member
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264
Original Poster
Rep:
|
Quote:
|
Originally Posted by paulsm4
I won't bore you with any details or extraneous subtleties. In Java, the *only* way to get an object is with "new". Which *always* allocates from the heap.
|
Don't worry. I am not all that easily bored, and always interested in knowing new stuff! Comparisons from Java to C++ might actually help me in further understanding the concept, as i think i am better in c++ than i am with java.
The book looks really good. I'll check it out as soon as i get a chance to.
|
|
|
|
03-09-2006, 06:40 PM
|
#13
|
|
Member
Registered: Jan 2004
Location: Connecticut, USA
Distribution: Slackware & Ubuntu
Posts: 53
Rep:
|
Thanks to all for this thread. I am in a java class now and was fairly confused by the professor. But after reading through this I have a much better grasp of it.
Thanks,
Phil V
|
|
|
|
03-09-2006, 11:37 PM
|
#14
|
|
Senior Member
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065
Rep:
|
> I am trying to find out WHY it has to be the way it is.
in addition to these good examples explaining why java is the way it is, you could also find some info on how a java virtual machine works.. some reading may shed some light on why java handles memory the way it does and why objects are created the way they are..
|
|
|
|
| Thread Tools |
Search this Thread |
|
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
All times are GMT -5. The time now is 02:27 AM.
|
|
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.
|
Latest Threads
LQ News
|
|