Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

fadilthrejk

[java] An explanation of classes and constructors. The tuts and books aren't working

This topic is 5560 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I made a class for the deck in my program, and it is REALLY crappy. I am not understanding what is going on in it at all. I have no idea what I''m doing, and I have read all of the tutorials and e-books I can find on classes and methods. I''ve hit a wall. Does anybody have some layman''s terms for what is going on when I make a constructor, instantiate, etc? Or a link to a COMPLETE idiot''s explanation of that stuff? Spread the rusty bleen ointment on the blue-red fromato with your thimble carver

Share this post


Link to post
Share on other sites
Advertisement
As you are aware, Java has built in types, like, int, float, double, boolean, etc...

What a class allows you to do is construct your own type, using the basic types, to make a better representation of what you are trying to emulate. For example, if you wanted to store someones height without a class, you might use float height and have it equal to feet or inches. But that also introduces a problem. You have to remember what you intended it to be and use it that way through all your code. Then the next guy to come along also has to know what it was used as. The next guy might even be you, six months after you last looked at your own code. With a class, you could model it a little more easily:

public class Height {
int feet;
int inches;
}


This way every one knows what the intent was.

When you instantiate a class, you are creating an object of that class. The class is like a blueprint for a house. You can buld 20 houses off one blueprint, so the blueprint is the class and each house is an instance of that class. Also, each house might have some modifications to it. One guy might want bay windows and another might want a 2 car garage. These are decisions that are made during construction. You instantiate and object with new. When new is called, memory is allocated and then the constructor is called. The constructor allows you to set up the each instance of the object according to a default, or with some customization. You could then define the Height class like this:

public class Height {
int feet;
int inches;

//don''t have the info yet, so set it to 0
public Height() {
feet=0;
inches=0;
}

//set the height according to user provided values
public Height(int f, int i) {
feet=f;
inches=i;
}
}


So now there are 2 ways to instantiate the height:

Height height1=new Height();
Height height2=new Height(6,4);


The first one gives you the default and the second one gives you a custom value.

As far as methods go, they are just functions, built into the class that allow you to affect and instance of that class. You might have:

public class Height {
int feet;
int inches;

//don''t have the info yet, so set it to 0
public Height() {
feet=0;
inches=0;
}

//set the height according to user provided values
public Height(int f, int i) {
feet=f;
inches=i;
}

public int getInches() {
return height*12+inches;
}
}


To get the total number of inches. With this you can get:

Height height2=new Height(6,4);
int inches=height2.getInches();


and inches will be 76 for this instance.




First make it work,
then make it fast.

--Brian Kernighan

"I’m happy to share what I can, because I’m in it for the love of programming. The Ferraris are just gravy, honest!" --John Carmack: Forward to Graphics Programming Black Book

Share this post


Link to post
Share on other sites
wow. all of those books i read have not been able to do what you just did. you explained it, and you gave me a CLEAR example. Thank you.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Bad authors! Go to your rooms!

Share this post


Link to post
Share on other sites
also, can I have the constructor set the value to ANY value, not just 0?

Spread the rusty bleen ointment on the blue-red fromato with your thimble carver

Share this post


Link to post
Share on other sites
Hi fadilthrejk,

have you tried Bruce Eckel''s "Thinking in Java" ?

It has the best explanation of object oriented programming basics in JAVA I''ve ever read. So if you''re familiar with basic syntax you might try this book. I started with it a few years ago (but don''t worry they keep it updated).

have a nice day

Share this post


Link to post
Share on other sites
quote:
Original post by fadilthrejk
also, can I have the constructor set the value to ANY value, not just 0?



Yes, you can.



----
David Sporn AKA Sporniket

Share this post


Link to post
Share on other sites
Fundamentally, a constructor is simply a way to automatically initialise your object. It provides an alternative to initialisation functions that have to be called manually (the reason why init functions are usually bad will follow). My Java''s rusty; apologies if there are syntax mistakes below:

public class BankAccount
{
// stuff here

// an initialisation function, not a constructor,
// so it must be called manually
public void initialise(Person accountHolder, int startAmountOfCash)
{
//super();
theAccountHolder = accountHolder;
wonga = startAmountOfCash;
}

public boolean withdraw(int amountToWithdraw)
{
if (wonga < amountToWithdraw)
{
beatPoorPersonWithAStick();
return false;
}

wonga -= amountToWithdraw;

return true;
}

private int wonga;
private Person theAccountHolder;
}


The above seems okay; you could do this:

BankAccount moneyHole = new BankAccount;
moneyHole.initialise(Bob, 42);


You''d have to remember to initialise it, every time, before using it! My word, that''s a nasty thing to have to do. What happens if you forget before using it? Possibly random crap (unpredictable behaviour), or something nasty (crashes through nulls, what have you), or bad results being returned from what you think is correct use of the class. Why chance it?

Constructors let you automatically initialise an object. Example:

BankAccount moneyHole = new BankAccount(Bob, 42); 


It''s now impossible to forget to initialise the object and it''s guaranteed to have a correct internal state! This can avoid nasty unpleasantness later on.

Think about this: a real-life object would have a state when it''s created, not assigned to it later. Can you imagine a world where a new mother hears "sorry, but this baby hasn''t been initialised. We can''t tell what its gender is until we initialise it. Hold on a sec", followed by sudden appearance of new parts on the baby?

Share this post


Link to post
Share on other sites

An excerpt from my favourite book (see my previous post for link) - Chapter 4: Initialization & Cleanup.
Don''t know if this is legal, but all credit is given to Bruce Eckel.

Guaranteed initialization with the constructor
You can imagine creating a method called initialize( ) for every class you write. The name is a hint that it should be called before using the object. Unfortunately, this means the user must remember to call the method. In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is
guaranteed.
The next challenge is what to name this method. There are two issues. The first is that any name you use could clash with a name you might like to use as a member in the class. The second is that because the compiler is responsible for calling the constructor, it must always know which method to call. The C++ solution seems the easiest and most logical, so it’s also used in Java: the name of the constructor is the same as the name of the class. It makes sense that such a method will be called automatically on initialization.

Here’s a simple class with a constructor:

//: c04:SimpleConstructor.java
// Demonstration of a simple constructor.
class Rock {
Rock() { // This is the constructor
System.out.println("Creating Rock");
}
}
public class SimpleConstructor {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
new Rock();
}
} ///:~

Now, when an object is created:

new Rock();

storage is allocated and the constructor is called. It is uaranteed that the object will be properly initialized before you can get your hands on it.
Note that the coding style of making the first letter of all methods lowercase does not apply to constructors, since the name of the constructor must match the name of the class exactly. Like any method, the constructor can have arguments to allow you to specify how an object is created. The above example can easily be changed so the constructor takes an argument:

//: c04:SimpleConstructor2.java
// Constructors can have arguments.
class Rock2 {
Rock2(int i) {
System.out.println(
"Creating Rock number " + i);
}
}
public class SimpleConstructor2 {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
new Rock2(i);
}
} ///:~

Constructor arguments provide you with a way to provide arameters for the initialization of an object. For example, if the class Tree has a constructor that takes a single integer argument denoting the height of the tree, you would create a Tree object like this:

Tree t = new Tree(12); // 12-foot tree

If Tree(int) is your only constructor, then the compiler won’t let you create a Tree object any other way.
Constructors eliminate a large class of problems and make the code easier to read. In the preceding code fragment, for example, you don’t see an explicit call to some initialize( ) method that is conceptually separate from definition. In Java, definition and initialization are unified concepts—you can’t have one without the other.
The constructor is an unusual type of method because it has no return value. This is distinctly different from a void return value, in which the method returns nothing but you still have the option to make it return something else. Constructors return nothing and you don’t have an option. If there was a return value, and if you could select your own, the compiler would somehow need to know what to do with that return value.

... end of excerpt ...

hope it helps you discover all the Java mysteries

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!