Jump to content

[tut] on Java Constructors.

Okay, I really have no idea about the demand for some of the topics I have in mind. So, I thought I might as well try and make a quick tutorial on some of the "closer" to basic concepts of Java. If there is some sort of demand for more of these, I can also do C++/C, python, and more Java. I am aiming for these tutorials to be for people that know the basic concepts, so their not for the beginners.

 

Introduction.

When talking with people that have switched out of Computing Science, one of the common issues/confusions that they had is the class system and constructors in Java. In this post I will attempt to explain constructors and then if this post isn't too long I will start explaining some of the class system.

 

Constructors

Okay, So constructors allow us to create objects. You will find out that you can pretty much put whatever you want in these objects (objects in object  :huh: ).

 

Constructors will have the same "name" as the class that they are contained in.

example:

public class Constructor_Class_Example{    Constructor_Class_Example()    {        //Stuff to put in object.    }}

Then you would have your main() right below of course.

 

Okay, pretty basic so far...

Check this out.

import java.util.Random;public class Constructor_TUT {	static Random n = new Random();	private int x, y;		Constructor_TUT(int _x, int _y)	{		x = _x;		y = _y;	}		public static void main(String[] args)	{		Constructor_TUT a = new Constructor_TUT(n.nextInt(),n.nextInt());		System.out.println(a.x);		System.out.println(a.y);	}		}

Okay, so allot has changed since the first example. Let's try to figure out what's going on here. We see the constructor, and a main(). We also have 3 global variables (n,x, and y). 

In main() we have a variable called "a" of type "Constructor_Tut". On that same line "new" is mentioned, this tells java that we need a chunk of memory of the size of type "Constructor_Tut". Then we run the constructor, we give the function two random integers. 

The constructor will take the two random variables and use them to set the corresponding global variables.

 

First "review" question:

In the following section of code (assuming this section is complete), will this code work/compile?

	static Random n = new Random();		Constructor_TUT(int _x, int _y)	{		int b= 5;	}	public static void main(String[] args)	{		Constructor_TUT a = new Constructor_TUT(n.nextInt(),n.nextInt());		System.out.println(a.b);	}}

Answer:

No, variables created inside of a function are not accessible from outside the function, constructors are still a function. The compiler will throw an exception saying "a.b" does not exist.

 

An Array of Objects.

Object arrays and Array lists is where I believe the confusion begins. Its too much to try to process at once, so I am going to try and break it down as much as possible.

 

In this image, I have made a visual representation of what is happening in memory.

Each object will get an index in the array of objects. I am still using the examples above, so x and y are both still random. In this image, the variable "a" contains the object pointers with the index's of 0-4 (inclusive).

EeJpRZt.png

The outermost box represents the amount of space the java has allocated for the program, the strip of numbers are the memory pointers,  and the smaller boxes represent each individual Object.

Now to turn this into code.

public static void main(String[] args){Constructor_TUT[] array = new Constructor_TUT[100];...

Okay, so this line asks java for a section of memory that will contain an array of pointers that can be set to the objects we create.

Second question. What will happen if I add the following line to the above code and I try to run it?

System.out.println(array[53].x);

Answer:

Null point exception, when you ask java for your array, it contains nothing.

 

So, now to add stuff to the array. The simplest way to do this is to use a for loop and create an object for each array point.

...for (int t = 0; t < 100; t++){     array[t] = new Constructor_TUT(n.nextInt(100),n.nextInt(100));}...

The completed program will look like this:

import java.util.Random;public class Constructor_TUT {	static Random n = new Random();	private int x, y;		Constructor_TUT(int _x, int _y)	{		x = _x;		y = _y;	}		public static void main(String[] args)	{		Constructor_TUT[] array = new Constructor_TUT[100];		for (int t = 0; t < 100; t++)	{				array[t] = new Constructor_TUT(n.nextInt(100),n.nextInt(100));		}                System.out.println(array[44].x);                System.out.println(array[34].y);	}	}

This program will create 100 objects with x and y in them. To call for an object in the array you simply call the variable the array is stored in, then the index of the object you want. Then you put a period then the name of the variable in the object you want.

 

Conclusion:

So yeah, that's how you use constructors, if you have any questions Ill be happy to answer them. Otherwise I will see how well this is received and will possibly make more of these quick tutorials. If there is a next, I will probably cover array lists and multiple classes next tutorial unless someone has something they specifically want to see. If I continue, I will show how to make graphical objects, and simple GUI online text chat clients.

I'm not aiming for this to be for beginners as you can see, I have skipped over many subjects that other beginner tutorials will cover.

Java tuts:


Constructors, possibly more to come.


221 Goodbye.

Link to comment
Share on other sites

Link to post
Share on other sites

Giving your class a private constructor and a main method is going to kill the re-usability of the code. There are of course situations where a private constructor might make sense, but this isn't one of them.

 

I should also mention that it makes the code next to impossible to unit test. Writing untestable code is generally a recipe for wasted time, or worse.

Link to comment
Share on other sites

Link to post
Share on other sites

Giving your class a private constructor and a main method is going to kill the re-usability of the code. There are of course situations where a private constructor might make sense, but this isn't one of them.

 

I should also mention that it makes the code next to impossible to unit test. Writing untestable code is generally a recipe for wasted time, or worse.

 

Thanks for pointing out the private constructor, I have it set in my mind that if the function doesn't have the intention of use outside of its class, without thinking about it I will set it to private. I had no intention of reusing this, so i just had a brain fart, ill go back and change them appropriately.

 

This is a very simple program, it doesn't even do anything useful, in fact all it does is consume memory, once it runs out of memory it throws an exception and dies. The purpose of this tutorial was to demonstrate the syntax and give an idea of what is happening.

Java tuts:


Constructors, possibly more to come.


221 Goodbye.

Link to comment
Share on other sites

Link to post
Share on other sites

Good job - I think these kinds of threads are beneficial to the community.

 

But... I'm a sucker for correctness so I have to correct you there. We may be arguing semantics but when you say:

 

Okay, so this line asks java for a section of memory that is the size of 100 Constructor_TUT objects.

 

You're actually allocating space for pointers to Constructor_Tut objects, not the objects themselves. That should be made clearer, even if that is not the topic being discussed.

Additionally, I subscribe to what SSL said. But other than that, keep them coming.

Want to solve problems? Check this out.

Link to comment
Share on other sites

Link to post
Share on other sites

-snip-

 

Thanks, I may get around to do more of them this weekend, Im not sure if I should make a new thread everytime or just keep adding to this one.

 

I was getting my information from Java Documentation. It literally says:

 

 

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.

So, yes you are right, I will fix that. The array is just an array of pointers to sections of memory.

 

EDIT: I have made the corrections

Java tuts:


Constructors, possibly more to come.


221 Goodbye.

Link to comment
Share on other sites

Link to post
Share on other sites

FYI "allot" means something very different to "a lot" which is what you meant to use.

Also I'm pretty sure you wrote more about arrays than constructors in this "constructor tutorial".

Link to comment
Share on other sites

Link to post
Share on other sites

FYI "allot" means something very different to "a lot" which is what you meant to use.

Also I'm pretty sure you wrote more about arrays than constructors in this "constructor tutorial".

 

And I thought I was aloof and dickish.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×