Crueld Hand said:
so I've just recently started learning about objects which I'm sure is obvious if you look at the threads I've been posting. What I don't really get is what the point of constructors even is. Aren't they essentially just variables?
A constructor is definitely not a variable. When you invoke a constructor, you are essentially creating an
instance of a class.
This
instance is what most people like to call an object.
So for example:
Account account1 = new Account();
Here you have just created an
instance of Account, or you have just created an
object of the Account class.
Now,
objects contain variables and methods.
To interact with these variables, an object usually invokes the appropriate method to change/set these variables.
Example:
Account account1 = new Account();
boolean deposited = account1.withdrawal(35.99);
System.out.println("Withdrawal successful: " + deposited);
// Located in another class... :
class Account {
double balance;
public boolean withdrawal(double amt) {
if( amt > balance ) // user wants to withdrawal more than they have!
return false; // not a good transaction
else // user has enough money to make this withdrawal
amt -= balance; //deduct the withdrawal amount from your current account balance
return true; //return the idea that this transaction was successful
}
Using the second skeleton of code you provided draws you away from the idea of encapsulation.
The code you provided:
public class Account {
double balance;
double initialBalance;
initialBalance = balance;
balance = 0.0;
}
This code works fine. But it can get ugly when using it. Let's build off of this.
If I wanted to make a withdrawal, I'd have to repeatedly program the same algorithm for each withdrawal.
Example:
//somewhere in public static void main(...) {...
Account account1 = new Account();
double balance = account1.balance;
double withdrawal = 35.99;
boolean successful;
if (balance < withdrawal )
succesful = false;
else {
successful = true;
account1.balance = account1.balance - withdrawal;
}
System.out.println("Successful transaction: " + succesful);
Now you'll have to repeat most of this code for each withdrawal you make. Compare that to:
Account account1 = new Account();
boolean deposited = account1.withdrawal(35.99);
System.out.println("Withdrawal successful: " + deposited);
As you can see, the
object makes a call to
withdrawal with a
paramater of 35.99
Behind the scenes we don't know what's happening(as an end-user) but we know more or less what is happening. (A withdrawal)
So in short, when you call a constructor, the JVM is allocating a spot in memory for your object. This spot in memory will hold the variables/methods of this object.
Primitive variables, have smaller space in memory because you cannot invoke any methods on them and well... variables don't have variables.