LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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

Reply
 
Search this Thread
Old 03-08-2006, 11:19 PM   #1
wwnexc
Member
 
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264

Rep: Reputation: 30
Arrow 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.
 
Old 03-09-2006, 12:09 AM   #2
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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.
 
Old 03-09-2006, 12:11 AM   #3
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
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.
 
Old 03-09-2006, 01:18 AM   #4
spooon
Senior Member
 
Registered: Aug 2005
Posts: 1,755

Rep: Reputation: 48
Quote:
Originally Posted by Mega Man X
Saab myCar = new Car();
you mean

Car myCar = new Saab();
 
Old 03-09-2006, 01:28 AM   #5
arunvk
Member
 
Registered: Nov 2005
Location: India
Distribution: Fedora 11
Posts: 194

Rep: Reputation: 30
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();
 
Old 03-09-2006, 02:40 AM   #6
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
Quote:
Originally Posted by spooon
you mean

Car myCar = new Saab();
Thank you
 
Old 03-09-2006, 03:28 AM   #7
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
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.
 
Old 03-09-2006, 09:30 AM   #8
wwnexc
Member
 
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264

Original Poster
Rep: Reputation: 30
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.
 
Old 03-09-2006, 09:44 AM   #9
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
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.
 
Old 03-09-2006, 12:59 PM   #10
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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.
 
Old 03-09-2006, 02:25 PM   #11
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
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!
 
Old 03-09-2006, 05:49 PM   #12
wwnexc
Member
 
Registered: Sep 2005
Location: California
Distribution: Slackware & Debian
Posts: 264

Original Poster
Rep: Reputation: 30
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.
 
Old 03-09-2006, 06:40 PM   #13
crewblunts
Member
 
Registered: Jan 2004
Location: Connecticut, USA
Distribution: Slackware & Ubuntu
Posts: 53

Rep: Reputation: 15
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
 
Old 03-09-2006, 11:37 PM   #14
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> 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..
 
Old 03-10-2006, 03:31 AM   #15
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
@crewblunts

I'm glad you liked it mate. I've made a few changes in the MainClass.java, to show quickly how inheretence works. Nothing fancy, I'm not a good programmer as paulsm4, mrcheeks or many others in this forum, but I do love Java

@xhi

Great suggestion. I found a few links about java VM that was worthy mentioning:

Java Virtual Machine:
http://en.wikipedia.org/wiki/Java_virtual_machine

Java Bytecode:
http://en.wikipedia.org/wiki/Java_bytecode

Google defination with several links:
http://www.google.se/search?num=100&...irtual+Machine

Regards!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
pointers or variables? lordofring Programming 7 06-29-2005 01:13 PM
Object Reference problem in Java servlets Hockeyfan Programming 1 06-16-2005 01:36 AM
passing variables by reference in javascript djgerbavore Programming 2 06-07-2005 11:34 PM
Java : Meta variables ? pycoucou Programming 7 04-16-2004 03:46 AM
what are c++ static constructors/destructors? cybercop12us Programming 2 01-24-2003 03:31 AM


All times are GMT -5. The time now is 12:35 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration