Jan 20, 2008

Extending the Possibilities

Alright! Hello everyone! Today we are going to cover inheritance! Inheritance is a fairly simple very powerful tool in the JAVA toolkit. A quick breakdown of what it is is that it allows you to take bits and pieces of code that are common among a group of relatable objects (Objects like say cats and dogs because they are both animals and will both have some of the same characteristics). It is similar to factoring out terms in math (or atleast that's how I see it though there are limits to this similarity that we'll get to). If you have:
2x +2
then you can do this...
2(x+1)

Same with our objects.

public Class Cat{
public void eat(){
//eating code
}
}
public Class Dog{
public void eat(){
//eating code
}
}

Both are animals and animals must eat. So this is how we factor out in java.

public Class Animal{
public void eat(){
//eating code
}
}

public Class Cat extends Animal{
}

public Class Dog extends Animal{
}

Since both the Cat and Dog classes extend animal they both will have the eat() method (The word extend is a keyword for this thing we call inheritance). This works for nearly every method that we put in animal now (We'll get to a couple of exceptions).

public Class Animal{
public void eat(){
//eating code
}
public void scratch(){
//scratching code
}
public void doTrick(){
//trick code
}
}

public Class Cat extends Animal{
}

public Class Dog extends Animal{
}

All these methods are now inherited by Cat and Dog. Cat and Dog will both inherit everything that is inheritable from the superclass (the class from which they inherit from). That being said you don't want a Dog to inherit a meow() method so all the methods within the superclass must be useable by the subclasses (the classes that inherit everything). The subclasses will also be able to inherit the instance variables, the variables that tell you about the state of the object.

public Class Animal{
String nameOfPet;
Int age;
}

Our Cat and Dog will now have both a nameOfPet and age. But what if there are two things that both Cat and Dog do but do differently? They both play but they play differently. We have a way to handle that and it links up rather nicely to the previous post on constructors (This is also where the factoring example loses it's usefulness).

public Class Animal{
String name;
Int age;
public void eat(){
//eating code
}
public void scratch(){
//scratching code
}
public void doTrick(){
//trick code
}
public void play(){
//standard play code that works for most animals
}
}

We'll say a dog plays like most animals

public Class Dog extends Animal{
}

We'll say a cat only likes to play with a ball on a string
public Class Cat extends Animal{
public void play(){
//specific code for playing with a ball on a string
}
}

That method in Cat overrides the method in Animal. The compiler will always use the most specific method when deciding which to allow the class to use. Our Cat play() method is more specific then the Animal play() method so it will use the Cat play() method. Now some different cases.

public class Animal{
private void morph(){
//morphing code
}
public void play(){
//playing code
}
}
public class Cat extends Animal{
public void play(Boolean haveALaserPointer){
//playing with laserpointer code
}
}

Alright so this is what happens here:
- our class Cat does not inherit morph(), this is because morph() is private (we'll do more with public, private, default and protected states later but right now public and private are what we are dealing with and for something to be inherited it cannot be private!)
- our class Cat inherits play() from Animal and creates it's own play method with the parameter Boolean haveALaserPointer. This connects very nicely with constructors because we had overloaded constructors which were different constructors with different parameters but they all existed. The same goes for methods and in this case we have two methods which means we have overloaded methods. The Cat class will have both in this case!

So now you have the basic breakdown of inheritance. But when do you use it? You use inheritance when two objects have a IS-A relationship. That is when some object is something else. For example a cat IS-A animal (I know the grammar isn't quite right) and a car IS-A vehicle. You don't use inheritance if the IS-A relationship doesn't work like a bear IS-A mule or a beer IS-A hotdog. Just doesn't work, they may have some of the same attributes like the bear and mule both being animals and the beer and hotdog both being something we consume but one does not stem from the other in the family tree. A beer may have something like this: Food to beverage to alchohol to beer. The hotdog may have some similarities but it does not come after beer in the family tree: Food to snack to hotdogs.

Summary and extra tidbits:
-inheritance is when one class inherits the attributes (methods, instance variables) from another class called the superclass that relates to it by a IS-A relationship
-the class that inherits these attributes is called the subclass
-methods can be overridden(another method in the subclass with the same name and parameters) and overloaded(same name different parameters)
-subclasses will have the overloaded methods and the original methods from the superclass
-inheritance can happen in many steps: Graeme can inherit from boys which can inherit from people which can inherit from ... and so on and so on.
-you cannot change public to private when overriding but you can when overloading (we'll talk about private in a later post).


I think that covered a lot. There is more, there always seems to be more with Java. But once again I'm tired. If you have any questions or you need anything cleared up comment and I'll see what I can do for ya.

Jan 13, 2008

Giving Objects Personality

Today we talk more about objects! Yay! Specifically how they are constructed. Last time we made ourselves a computer object. If you recall the line that instantiated [made] the object looked like this:

Computer myComputer = new Computer();

and follows the format:

ClassName objectName = new ClassName();

Now Computer() is called a constructor. This looks and acts a lot like a method but it isn't! It is a constructor! A constructor is the code that runs when a new object is instantiated [made], it customizes your object for you if you give it the proper information and have a constructor made to take that information. Now we didn't make a constructor for our last program but the compiler made one for us! The compiler automatically made the constructor for us because we didn't make a constructor ourselves and it looks something like this:

public class Computer{
public Computer(){
}
}

Now that's not a very good constructor, it doesn't give the object any attributes. In our last program we used methods to change instance variables we'll use a constructor to set a few new ones in this case.

Note: Notice how constructors are different then methods! First constructors have the exact name of the class. Second methods have a return type (so far we have only seen void which means no return type).

Now constructors can take in information and use it to change the instance variables of an object or you can just change the instance variables without taking in any information, like a default. Some examples of constructors:

*we'll give our computers some different instances variables for the purposes of this example (all the following code would go within the braces for the Computer class):

int hardDriveSizeInGB;
double processorSpeedInGHz;
int numOfUSBPorts;

public Computer(){
hardDriveSizeInGB = 250;
processorSpeedInGHz = 2.8;
numOfUSBPorts = 3;
}
public Computer(int hardDrive, double processor, int ports){
hardDriveSizeInGB = hardDrive;
processorSpeedInGHz = processor;
numOfUSBPorts = ports;
}
public Computer(int hardDrive)
hardDriveSizeInGB = hardDrive;
processorSpeedInGHz = 2.8;
numOfUSBPorts = 3;
}

Now each of these is different. Which one is called is dependant on what you give the constructor in the declaration.
Computer myComputer = new Computer(300);
This will call our third constructor because it satisfies the needs for it's parameters. Same works for the other two.
Computer myComputer = new Computer();
Computer myComputer = new Computer(300, 4.4, 12);
They will call their respective constructors. But make sure you give the correct parameters for atleast one of your constructors otherwise it'll blow up in your face. Now if we didn't have our first constructor with no arguments the compiler will no longer make it automatically for us. As soon as you have one constructor made it won't bother.

Note: Having more than one constructor for a class is called having overloaded constructors.

Common mistake! You must make constructors with different argument lists. Meaning you can't have two constructors that just take two integers, the compiler doesn't know which one to call and it will blow up.

One last tidbit, there are other things you can do within constructors like verify that what is being put into the constructor is feasible. Take this example:

Computer obsenelyHugeHD = new Computer(20000)

public Computer(int hardDrive)
if (hardDrive <>
hardDriveSizeInGB = hardDrive;
} else {
hardDriveSizeInGB = 250;
}
processorSpeedInGHz = 2.8;
numOfUSBPorts = 3;
}

That's all for constructors for now. There is more though! But we'll cover that another day, I'm tired. If you have any questions leave a comment and I'll clear it up the best I can.

Jan 7, 2008

Getting Object Oriented

Alright! So this post is all about objects! JAVA itself is an object-oriented language meaning that pretty much everything revolves around objects. Objects are instances of something that have a current state and can do things. Such as my computer, it is on and it is inputting what I’m typing. So really objects can be about anything. Now how do we make ourselves an object?

We have already made code that has the main elements in java:
classes
main() method
variables
statements

Now let’s start building ourselves a small program and we’ll make it about a computer.

public class Computer{
public static void main(String[] args) {

}
}

Now we are going to give our computer it’s state, or in other words what it is currently with what are called instance variables.

public class Computer{
boolean isOn;
String typeOfComputer;
String currentScreen;

public static void main(String[] args) {

}
}

Now we are going to add a couple of methods. Methods are what we use to control the instance variables.

public class Computer{
boolean isOn;
String typeOfComputer;
String currentScreen;

public static void main(String[] args) {

}

public void turnOn() {

}
public void changeType() {

}
public void changeCurrentScreen() {

}
}

turnOn(), changeType() and changeCurrentScreen() are our methods but they don’t do anything... So we’ll give them something simple to do that corresponds with their name.

public void turnOn() {
isOn = true;
}
public void changeType() {
int x = (int) Math.random() * 3 + 1;
if (x == 1){
typeOfComputer = "Mac";
} else if(x == 2){
typeOfComputer = "Alienware";
} else if (x == 3){
typeOfComputer = "Super Computer";
}

}
public void changeCurrentScreen() {
int x = (int) Math.random() * 2 + 1;
if (x == 1) {
currentScreen = "Home screen";
} else if(x == 2) {
currentScreen = "Google";
}
}

The turnOn() method now turns on our computer
changeType() method now randomly changes the type of computer
changeCurrentScreen()method now randomly changes our computer screen

Couple tidbits that need to be explained...
int x = (int) Math.random() * 3 + 1;

within the method we are declaring some integer x, we’ll talk about it more later on (not today) but x only exists within the method it is declared then it dies. You can’t use it elsewhere unless you declare it again.

The (int) casts the random number we make between 1 and 4 into an integer, it truncates it therefore giving us 1, 2 or 3.

Now it’s nice and all having these methods but how do we use them? We have to call/invoke them.

So we’ll try this...

public static void main(String[] args) {
turnOn();
changeType();
changeCurrentScreen();
}

Won’t work...

The computer does not know what you are talking about. We have the code for our method to control our object but we have no object and we haven’t actually made those controls we have just wrote the code for them (I’ll admit that sounds a little confusing for the moment).

To create our Computer object we need a line of code that looks like what follows:

Computer myComputer = new Computer();

When we create this myComputer object it creates everything within the class so we have also made the methods/controls for this object and this object must be created before we can do anything to it so we'll put it first in the main() method.
This is a statement that creates a new Computer object called myComputer. All these statements generally follow this format:

ClassName objectName = new ClassName();

ClassName is the name of the class that you want to create, the object that you want to create.
ClassName() is called a constructor and you need those brackets, we’ll do more with constructors later.

Now we can fix our code and tell the computer what we want it to do and what we want it to do it to.

public static void main(String[] args) {
Computer myComputer = new Computer();
myComputer.turnOn();
myComputer.changeType();
myComputer.changeCurrentScreen();
}

Then there is just one last thing we need to do with our program. We did all of these changes to myComputer but what do we have to show for it? Bupkiss. So we’ll make another method to display our info.

public void display() {
System.out.println("Is the computer on? " + isOn);
System.out.println("What type of computer is it? " + typeOfComputer);
System.out.println("What is the current screen? " + currentScreen);

}

Remember that the “+” concatenates strings and the variables together.

Then you just have to invoke this method after you have changed the instance variables and your good.

public static void main(String[] args) {
Computer myComputer = new Computer();
myComputer.turnOn();
myComputer.changeType();
myComputer.changeCurrentScreen();
myComputer.display();
}

So our whole code ends up being:

public class Computer {
boolean isOn;
String typeOfComputer;
String currentScreen;

public static void main(String[] args) {
Computer myComputer = new Computer();
myComputer.turnOn();
myComputer.changeType();
myComputer.changeCurrentScreen();
myComputer.display();
}

public void turnOn() {
isOn = true;
}
public void changeType() {
int x = (int) Math.random() * 3 + 1;
if (x == 1){
typeOfComputer = "Mac";
} else if(x == 2){
typeOfComputer = "Alienware";
} else if (x == 3){
typeOfComputer = "Super Computer";
}

}
public void changeCurrentScreen() {
int x = (int) Math.random() * 2 + 1;

if (x == 1) {
currentScreen = "Home screen";
} else if(x == 2) {
currentScreen = "Google";
}
}
public void display() {
System.out.println("Is the computer on? " + isOn);
System.out.println("What type of computer is it? " + typeOfComputer);
System.out.println("What is the current screen? " + currentScreen);

}
}

That was a lot but it covers a massive concept, or at least a small part of a large concept. Hope this is understandable, if not tell me and I'll see what I can do!

Good night!

Dec 20, 2007

Would You Like Some Variables As Well?

On a quick note beforehand... how did you find the looping post? I may end up redoing it for you guys if you didn't "grok in fullness" because I may not have done it justice, the <> statements blogger really doesn't like and I had to rewrite the whole thing a couple times. Am searching for another method to show proper form currently (but for now examples won't be tabbed in).

Alright so we have used variables already but they weren't really explained in any sort of detail. Variables are a sort of container but they are picky containers. Tupperware with attitude. If you try to put something in it it doesn't like it spits it back out with a nasty error message. To declare a variable you must say what type it is and give it a name. To use a variable it must be initialized. So here is an example of a statement declaring a variable:

int x = 0;

The int is the type of variable x is.
x is the name of our variable.
= 0 initializes our variable.

We can also declare a variable and initialize it in two steps:

int x;
x = 0;

Now for our purposes at the moment our variables are going to go inside our main() method. This is for reasons that will be explained in upcoming lessons.

Now you aren't just going to want to use integers. You are going to want to use many different types of variables. Here is a list of the variables for you:

int, these are integers and can store positive and negative nondecimal numbers.
boolean, these are true and false operators and must be set to true or false.
byte, can hold values from -127 to 128 according to this site.
double, can hold decimal values.
long, can hold really long nondecimal numbers, kind of like a super integer.
char, can store characters like "j" or "a".
String, can hold a bunch of characters strung together, like "hello there" or "ass22d&&^(*".

There we are, toy with those at will, we'll get them out of the main() method next time.

Dec 19, 2007

Our Methods are Getting Loopy

Hello, the post may be a little messed up, blogger really doesn't like < pre >!

Today we are going to learn "loops". Loops are a way of repeating code over and over and over and so on... There are a couple types of loops in JAVA, "while", "do-while" and "for" loops. We will do "while" and the basic "for".

The while loop:
- while some condition is true the loop will run.

while (some condition) {
//code to run
}

An example of this:

while (x > 0) {
//code to run while x > 0
}

The for loop:
- this type of loop is for some code that you know needs to run a certain amount of times. These are basically a while loop with a sort of counter built in.

for (some variable; condition; increment/decrement) {
//code to run
}

An example of this:

for (int x = 0; x < 5 ; x = x + 1) {
//we declare a variable x and set it to zero
//more on declaring variables later
//this will run when x < 5
//x will go up by one each time the loop runs through
}

A couple of things we have to go over here:
1) The "//" indicates a comment. A comment is a piece of writing that java ignores. It just skips merrily along right over it. "//" is used for 1 line comments.

2) "/* your comments */" is for larger comments. All writing in between the /* */ is ignored.

3) Operators... the <, >, != and == are your basic operators. THERE ARE 2 EQUALS SIGNS THERE! This is on purpose, when comparing two values you use TWO EQUALS SIGNS! When setting something equal to another thing you use one equals sign. The != means not equal to.

4) You can also combine these operators, <= and >=, less than or equal to and greater than or equal to. For a complete list go here.

So now let's make a small program with some of the things we know. We'll make it display a message a certain amount of times.


public class Display {
public static void main(String[] args) {
for (int x = 0; x < 5; x = x + 1){
System.out.println("Counting: " + x);
}
}
}

The output to the command line for this will be:
Counting: 0
Counting: 1
Counting: 2
Counting: 3
Counting: 4


The x is incrementing so you will see it go up by one each time starting from 0. Notice the x = x + 1 only runs once the loop has gone through once and not immediatly.

The line:
System.out.println("Counting: " + x);
Notice that this is not:
System.out.print("Counting: " + x);

.print prints continuously on one line.
.println print to a new line each time.

Also in that line we have "Five times" + x
The "+" in this acts to combine the two for output. It concatenates it, joins them together.

The while loop itself is a bit simpler:

public class Display2{
public static void main(String[] args) {
int x = 0;
while (x < 5) {
x = x + 1;
System.out.println(x);
}
}
}


This will give us an output of:
1
2
3
4
5

This is enough to soak in for one day. We'll start making some simple programs soon so we can get this deep in our heads.

Dec 18, 2007

An Iffy Brew

Hello everybody,

Today we make some decisions, well the computer will. We are going to do "if" tests(! These are core elements that allow computers to make decisions that are based on a condition.)

If's take the general form of...

If (argument) {
code to run if true
}

The argument can be many things, generally they compare two things but it can be a boolean (true or false variable).
You can add an else as well...

If (argument) {
code to run if true
} else {
code to run if false
}

So to try this out we'll make a quick program to check if a number we generate is greater than or less than fifty.

public class OddOrEven{
public static void main(String[] args) {

double z = Math.random() * 100;
if (z <>
System.out.print("Less than 50");
} else {
System.out.print("Greater than 50");
}
}
}

We have our class in blue because all programs need a class.
Then we have our main method, it is the method that runs first.
In purple we have our statements
-
double z = Math.random() * 100;
-"double z" declares a double(a decimal value that can hold more information then a single) named z
-"= Math.random() * 100 " generates a pseudorandom number from 0 to 1 (computers can have true randomness), by multiplying by 100 we get a number between 0 and 100.
In brown we have our if else block.

If statements can also be nested which means an if block within an if block.

if (argument) {
code to run if just the first one is true
if (argument) {
code to run if both are true
}
}

Why don't you try to make a program that checks if the integer z is > 50 and if it is check if it is less than 75 and if z <> 25.

Good luck!
My sample answer is here.

Dec 17, 2007

Your Basic Blend

Hello there!

Alright so now we get to some of the basic code structure of Java!

First we have the source file.
- Inside your source file you put your classes.
-Inside your classes you put your methods.
-Inside your classes you put your statements.

A source file is a file with a .java extension.
Then inside your source file you have (this would be in your text editor):
(P.S. these statements should be tabbed but blogger takes them out. I'll get on it)

public class Heater {
void heat() {
1stStatement;
2ndStatement;
}
}

So let's make the traditional initiation program "Hello World".

We know it must have a source file, class(es) , method(s) and statement(s).

file HelloWorld.java (in text editor save it as a .java)

public class HelloWorld {
public static void main (String[] args) {
System.out.print("Hello World");
}
}

Alright let's break that down...

public class HelloWorld {
-the public means it can be accessed by all
-class means it is a class...
-HelloWorld is the name of the class
-you must open the class with a brace {

public static void main (String[] args) {
- once again public means it can be accessed by all (as opposed to private which we'll get to)
- static we'll do later
- void means it is a method with no return type
- main() is the name of the method, the main() method always runs first!
- (String[] args), this is a line that creates an "array" of strings and were calling that array args and is a parameter of main(). This allows for information to be entered into the program from the command line as far as I know.
- you must open the method with a brace {

System.out.print("Hello World");
-System.out.print puts the string(characters, letters, numbers strung together) that is in the parenthesis () and quotes "" into the command line.
- you must end a statement with a semicolon ;

Then you finish up by closing the method then the class.

Now we want to run this.
First we must compile this into a .class file.
Navigate to the folder your file is in in command prompt (unsure for mac)
Type dir to check that the .java file is in the directory.
Then now that we have the Javac command because of the last post type:
javac HelloWorld.java

If there are no errors in your program this will compile. Otherwise your going to get some odd messages. I'll put some common errors and errors I made when I first did this.

- Java is case sensitive, capitols matter!
- All statements must end with a semicolon!
- Your string must be within quotes!
- You must open classes and methods with opening braces!
- You must close classes and methods with closing braces!

Alright so if you have your .class file now you can type (still in the same directory):
java HelloWorld
and voila! You get the uber-exiting message Hello World.

Now that you have that you can edit your original code to make that say whatever you want. If you want the message to appear on new lines you just have to put in another identical statement with a different string. Have fun!