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!