Website Design United States, Website Design California, Website Designing United States, Website Designing California

Introduction to Classes

Classes are at the very core of Object Oriented Programming. A class defines the properties and methods of an object. Whether you know it or not you have already been working with classes and objects. The Java Runtimes are packed with a large amount of classes you can use. There are two main types of data types: primitive and object. Primitive data types hold only one piece of data and do not have and do not have properties or methods (i.e. int, double, long, etc). Objects are what we will be discussing in these tutorial lessons.

During this tutorial I mention We or You quite a bit. This means you the reader of this tutorial that is hopefully following along and creating these classes. When I say They I mean the users (programmers not end users) of these classes. When you write classes you are doing the job of the Author (no not writing books). When you use these classes in your program you are the developer (They).

You can think of a Class as a blueprint of an object. It maps out all the properties and methods and what each property and method will do.

Lets start with the beginnings of a class. Open your Java editor and create a new class called Square. You should end up with the following:

public class Square
{

}

Now lets give this class some basic properties and methods. Since this is just an introduction I will keep it a simple class. Classes are based on real life objects so now we must think what a square has. The first thing I think of is the four sides and since it is a square all four side are the same. So it will have a Length property. Going back to grade school math you could also calculate the the Area by Length2.

Lets start with the Length property. There are four (4) main types of properties: read/write, write once, read only, and parameter. Read and writer properties can be read and changed however many times as you need. Write once properties can be set (changed) only once and read however many times you need. Read only properties cannot be set but can be read however many times you need. I will explain parameter properties later on in this tutorial.

Now we will focus on the Length. Ask yourself can a length be negative or even zero? No! Can it have a decimal? Yes! So we have to program that. Since there can be a decimal lets declare it as a double data type. We have decided that Length will have to be validated since it must be greater than zero. Therefore we must use Get and Set methods. These are no different than any other method but they are a standard for making your own classes. We will also need a variable to hold the Length. This variable will be class level so that it cannot be directly accessed outside of the class. You should end up with code similar to this:

private double length;

public double getLength()
{
return length;
}

public void setLength(double len)
{
if (len > 0)
length = len;
}

When you want to get the value of Length you would call getLength. When you want to change the value of Length you would call setLength supplying the new Length. As we mentioned there is a check to ensure Length is greater than zero. Q: What do I do if the number is invalid? A: That is up to you. You could simply ignore it or throw an Exception. We are currently just ignoring but you could throw and exception if you wanted.

public void setLength(double len)
{
if (len > 0)
length = len;
else
throw new IllegalArgumentException("Length must be greater than zero");
}

Ultimately the decision is yours. Also the type of exception and message you display are also your decision but both should be applicable to the situation.

Now for the method. Area calculates something which I might want to know. So the method will return a value.

public double Area()
{
return length * length;
}

The final code for the class should look something like this:

public class Square
{
private double length;

public double getLength()
{
return length;
}

public void setLength(double len)
{
if (len > 0)
length = len;
else
throw new IllegalArgumentException("Length must be greater than zero");
}

public double Area()
{
return length * length;
}
}

How about another example? As I mentioned early there are Parameter properties and I said I would show you one. Parameter properties can be read/write, write once, or read only as well. It all depends on the situation. Lets continue with another class called Triangle. As mentioned before, a triangle has a list of its sides and has three (3) sides in all. To store this you need an array of doubles. Q: How do I know which side they want to set when it is one property? A: They also supply the index (0 to 2) of the side they wish to change. Now you have to check that they set it to a valid number and supply a valid index. Again what you do if they supply invalid values is up to you.

private double[] sides = new double[3];

public double getSide(int index)
{
if (index < 0 || index > 2)
throw new IndexOutOfBoundsException("index must be 0 to 2");
else
return sides[index];
}

public void setSide(int index, double sideLength)
{
if (index < 0 || index > 2)
throw new IndexOutOfBoundsException("index must be 0 to 2");
else
if (sideLength > 0)
sides[index] = sideLength;
}

A triangle also has a Perimeter and Area but calculating them is different then a square. Remember the area of a triangle is Base * Height / 2 but we don't know the base or height. We do know the base is one of the sides and the height is a perpendicular line going from where the other two lines meet to the base. So you can either have a new property to keep track of the base and another for the height or make one of the elements of the side the base and have another for height. I will do the second option and have a public constant to show which element is the base. There will also be an example of a read only property. A read only property simply has just a Get method.

public static final int BASE_INDEX = 0;

private double height;

public double getHeight()
{
return height;
}

public void setHeight(double h)
{
if (h > 0)
height = h;
}

Then you can calculate the Perimeter and Area.

public double parameter()
{
return sides[0] + sides[1] + sides[2];
}

public double area()
{
return sides[BASE_INDEX] * height;
}

The meaning of static will be explained later on in the Instance vs. Class lesson and the meaning of final is explained in Introduction to Inheritance.

You may have been wonder when the object is first created that all the variables are zero which is invalid. Also is there something that is called when we create an object of the class. Well yes, the "Constructor" is called when you create an object of the class and you would put the code in there. Which brings me to method overloading. Method overloading is having more than one method with the same name but a different parameter list. Lets stick with the Triangle class as the example. We will have two constructors: one with no parameters and another will accept all the three sides and height. A constructor is a method that has no return type (not even void) and usually (but not a must) has the same name as the Class.

public Triangle()
{
defaultValues();
}

public Triangle(double baseLength, double secondLength,
double thirdLength, double triangleHeight)
{
// set the default values to ensure a valid Triangle
defaultValues();
// attempt to set the values given
setSide(0, baseLength);
setSide(1, secondLength);
setSide(2, thirdLength);
setHeight(triangleHeight);
}

private void defaultValues()
{
sides[0] = 1;
sides[1] = 1;
sides[2] = 1;
height = 1;
}

You may be wondering why I set the defaults in both of the constructors. Just because they supply the parameters doesn't mean they will supply valid values. So the second constructor sets the defaults and then tries to set the values.

Your final code for the Triangle class should look similar to this:

public class Triangle
{
public static final int BASE_INDEX = 0;

private double[] sides = new double[3];
private double height;

public Triangle()
{
defaultValues();
}

public Triangle(double baseLength, double secondLength,
double thirdLength, double triangleHeight)
{
// set the default values to ensure a valid Triangle
defaultValues();
// attempt to set the values given
setSide(0, baseLength);
setSide(1, secondLength);
setSide(2, thirdLength);
setHeight(triangleHeight);
}

private void defaultValues()
{
sides[0] = 1;
sides[1] = 1;
sides[2] = 1;
height = 1;
}

public double getSide(int index)
{
if (index < 0 || index > 2)
throw new IndexOutOfBoundsException("index must be 0 to 2");
else
return sides[index];
}

public void setSide(int index, double sideLength)
{
if (index < 0 || index > 2)
throw new IndexOutOfBoundsException("index must be 0 to 2");
else
if (sideLength > 0)
sides[index] = sideLength;
}

public double getHeight()
{
return height;
}

public void setHeight(double h)
{
if (h > 0)
height = h;
}

public double parameter()
{
return sides[0] + sides[1] + sides[2];
}

public double area()
{
return sides[BASE_INDEX] * height / 2;
}
}

To do the same thing for the Square:

public Square()
{
length = 1;
}

public Square(double len)
{
length = 1;
setLength(len);
}

Now lets test! Create a new executable class.

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

}
}

Within main we can test the classes we made. Create a variable and object of Triangle and play around with its methods.

Triangle t = new Triangle();
System.out.println("Perimeter: " + t.perimeter() +
" Area: " + t.area());
t = new Triangle(6, 5, 5, 4);
System.out.println("Perimeter: " + t.perimeter() +
" Area: " + t.area());

Notice the first time we create a Triangle we use the constructor with no parameters so we get a default triangle. The second time we supply a valid 3 sides and a height and therefore we get different values from the perimeter and area.

WEB DESIGN INDIA
42 B Malviya Nagar , New Delhi-110017

Skype: manmeetsi
Email: support.webdesignindia@gmail.com
Tel: 91-011-40502005, 9810067295

 















 


© 2008-2009 dotnet4all.com