• (2 Pages)
  • +
  • 1
  • 2

How to Create Your Own Objects in Java Rate Topic: ***** 3 Votes

#1 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 05 July 2011 - 06:53 PM

*
POPULAR

Hello all, this is my first tutorial so if you have any problems with the tutorial please let me know and I'll make any changes needed. I'm going to start the tutorial off with an introduction of how Object Oriented Programming (or OOP) works and why it is so powerful, I will then go over the basic concepts of OOP and what is needed to know to make your own objects, I will then follow up with a step by step example of a Rectangle object. This tutorial assumes you know the basics of the Java programming language, its concepts and have some programming knowledge already. If you have never programmed in Java before I suggest you read an intro to Java tutorial before reading this tutorial.

Introduction:

To start things off I'm going to go over what you will and what you won't learn in this tutorial. First off I won't be covering anything about inheritance in this tutorial, this is strictly a beginners tutorial on how OOP works and I don't want to be throwing too much information right off the bat. Depending on how well this tutorial turns out I will create a part two that goes over more advanced topics like inheritance, and polymorphism. This tutorial WILL cover the basics of creating your own objects, good practices for creating objects and why using OOP over procedural oriented programming is much more efficient and better.

Why OOP?
Object's are one of the most powerful tools a programmer has, it allows the programmer to easily reuse code, create a data type for a specific task, and easily manage data without worrying about it changing or becoming stale through the use of encapsulation. Objects should be used whenever possible to save in development time and code needed to write. If you look at the Java API you'll see an almost endless list of objects to do just about any task you would want to do.


Basic Terms:
Class- A class is the blueprint of the object that you will be creating, it is where you build an object. Every instance of the object you created uses your class to build it.

Instances- Instances are simply an object with its own set of data. When you create an object each object gets its own set of data separate from all the other instances of the same object. Each instance is unique.

Constructor- This is what will be used to create an object, it dictates what information should be passed to the object (if any) at the time of its creation and is the first thing that is called when an object is created. There can be multiple constructors for a single object.

Fields (or Attributes)- These are the variables you use to store the information in your object. Objects can contain any number of fields of any data type.

Methods- This is what you will use to change the state of a field, grab the state of a field or perform a calculation on a field. Methods are split up into two main categories, setters and getters (also known as mutators and accessors respectively).

Encapsulation- This is used to keep the fields integrity safe from being changed outside of the object. Instead of giving the programmer that is using your object direct access to the objects fields you give them methods that are used to modify and access the fields.Access specifiers are used to allow (or not allow) access to the data contained in the fields in your object. Methods are usually public while fields are usually private (this will be explained in more detail later in the tutorial).

Static- When a method is static it means it doesn't need an instance of the object to be created to use the method. This may not make much sense now but it should by the end of the tutorial.

Method Signature- A method signature is what defines a method. There are six components to a method, which will be covered later in the tutorial.

UML Diagram- A UML diagram is a tool that programmers use when creating objects. It allows the programmer to view and build the object from an abstract level.

What is an Object?
You may be wondering what an object is and what you would ever need to use one for. Well if you've ever used a Scanner to get input from a user then you have used an object before. In fact you've most likely used dozens of objects before without even knowing it. An object is a kind of data type that you use to complete a specific task or store data about a specific entity. Objects have certain traits and certain behaviors that make them different from other objects. Think of an object in programming as any old object in the real world, for example a car. What traits does a car have? Well a car has a make, model, color, and mileage (obviously there are more traits for a car but we're just going to cover the basics). What behaviors does a car have? A car starts, goes forward, goes reverse, parks, and turns off. These are the most basic of features a car has, obviously there are other objects that are more simple then a car, like a switch. A switch has only two traits, on or off and has two behaviors, close the circuit or open it. When you create a software object you will be doing this exact process, determining what traits the object should have (also known as fields or attributes) and what behaviors the object will perform (also known as methods or functions).

Taking A Look At the Code

Now that you understand what an object is made up of we can start to take a look at some code and understand what it means. First we're going to look at the syntax for a constructor and some sample constructors. Then we're going to do the same thing for methods.

Constructor and Method Syntax
Below we have the syntax for a constructor. The constructor header is the first line of the constructor, it tells us what the constructors name is, what has access to the constructor (will be explained in more detail) and what parameters the constructor takes if any. There are two rules you must follow when you make a constructor:

1. A constructor must have the same name as the class that it is in (i.e. if you created a Car class you must have your constructors name be Car too).

2. If there is more then one constructor for a class they must not have the same header (i.e. you can't have two constructors in the same class with the header public Car(), they must be different).

   AccessSpecifier ConstructorName(Parameter Variable Declaration) {
      //Do something
   }



Above is the syntax for a constructor. The access specifier is what determines what code can see and use this specific constructor, there are three values it can be, public, private and protected. Public means that code that is outside of the constructors class can see and use it. Private means only code inside of the constructors class can see and use it. We're not going to go over what protected means as it is not in the scope of this tutorial.

After the access specifier you must type the constructors name (remember the constructors name must be the same as the class name) followed by a pair of parenthesis. These parenthesis can be left blank or contain Parameters. If a constructor contains a parameter you must declare the parameters data type followed by the name of the parameter. If a constructor contains 2 or more parameters you must declare the data type and name for each parameter, even if the parameters are of the same type (i.e. you can't do the following public Rectangle(Double w, h) as it will cause an error).


Now lets take a look at some sample constructors. The first constructor is for the class Car and doesn't have any parameters. In most cases a constructor like this would set the fields of the object to 0 or null.

   public Car() {
      //Do something.
   }



This next constructor is also for the Car class but this time it takes an argument of type Double called m. The constructor takes the value in m and assigns it to the mileage field (the this keyword is used to reference the current object being used).

   public Car(Double m) {
      this.mileage = m;
   }



Below is the syntax for a method. As you can see it looks a lot like the syntax for a constructor except for one difference, a method has one more field called a return type (along with one optional field called static). The return type field is used to specify what type of value (if any) should be returned when the method is done executing. You can have the return type be anything from String to int as long as it is a valid data type. You can also have your method return any type of object. The last value a method can return is void, which means "don't return anything". One other not so obvious difference between a constructor and method header is the method name, since it isn't a constructor you can name the method any legal name. That being said there are some guidelines for naming methods (I say guidelines because you don't have to follow them but it is good practice to do so). Remember that we use our methods to access our fields in our class, because of this methods are almost always set to public.

1. The first letter of the method should be lowercase, followed by camel case (i.e. getField()).

2. For getter and setter methods you should have the first word of the method be get or set respectively.

   AccessSpecifier ReturnType methodName(Parameter Variable Declaration) {
      //Do something
   }



Now lets look at some sample methods. We're going to look at both setter and getter methods. The first method is a setter method, notice how its return type is void. This is because when we set a field in our class we don't need to return anything, just set it. We instead set up a parameter and assign the value of the parameter to the value of the field we want to modify.

   public void setField(int f) {
      field = f;
   }



Next we have a getter method with the return type of String. Whenever a method has a return type you must have the keyword return in your method. This keyword must then be followed by a variable or value of the return type (i.e. you can't have a return type of String and try to return an int, it will give you an error).

   public String getField() {
      return field;
   }



Creating an Object

The first thing we want to do is decided what type of object we want to create. For this tutorial I'm going to create a Rectangle object as they are easy to understand, don't contain many fields or methods and is the unofficial universal beginning object. Before we jump into coding we need to think about what fields we should have for our Rectangle object. A rectangle contains both a height and width, those will be our fields. For our methods we can do a few things, we can have our rectangle compute its area and perimeter, along with set its length and width, and return its length and width. Below is a Rectangle class that I wrote along with a UML diagram of the Rectangle class:


public class Rectangle {
	//These are the fields used to store the width and height of your Rectangle object.
	private double width, height;

        //This is a static field used to keep track of the number of Rectangle object instances.
        private static int counter = 0;
	
	//Constructor for the class, used to set up all data when a 
	//Rectangle object is created. This default constructor creates
	//a Rectangle object with a width and height of 1.0
	public Rectangle() {
		width = 1.0;
		height = 1.0;
                counter++;
	}
	
	
	//This is another constructor for the Rectangle class that accepts
	//two arguments that are of the type double. This is what the you
	//will use when you know what the width and height of the Rectangle
	//object is when you create it. The constructor takes w and h and 
	//sets them equal to width and height respectivley.
	public Rectangle(double w, double h) {
		width = w;
		height = h;
                counter++;
	}
	
	
	//This is a setter method, it is used to change the value of width
	//to whatever w is.
	public void setWidth(double w) {
		width = w;
	}
	
	//This is a setter method, it is used to change the value of height
	//to whatever h is.
	public void setHeight(double h) {
		height = h;
	}
	
	//This is a getter method, it is used to retrieve the value of width
	//at the current time.
	public double getWidth() {
		return width;
	}
	
	//This is a getter method, it is used to retrieve the value of height
	//at the current time.
	public double getHeight() {
		return height;
	}
	
	
	//Here is the getArea method, it uses the width and height 
        //field that is stored in your rectangle object to
	//calculate the area.
	public double getArea(){
	   return width * height;
	}
	
	
	//Here is the getPerimeter method, it uses the width and height 
        //field that is stored in your rectangle object to
	//calculate the perimeter.
	public double getPerimeter(){
	   return (2*width) + (2*height);
        }
        
        //Here is a static method used to count the number of Rectangle instances
        //are currently created.
        public static int getInstances() {
           return counter;
        }
}



Posted Image

Now lets take a look at the code one block at a time. First lets look at the fields in the class:

private double width, height;
private static int counter = 0;



As you can see both of these fields are doubles and private, this means that code outside of the rectangle class can't directly access the width and height fields. Since the fields are private it helps keep the data's integrity through encapsulation. Under the width and height field you'll see a field called counter that has the keyword static between private and int. When this keyword is used it allows us to access the data without needing an instance of the object created.

Next we're going to look at the two constructors for the rectangle class:

   public Rectangle() {
	width = 1.0;
	height = 1.0;
        counter++;
   }

   public Rectangle(double w, double h) {
	width = w;
	height = h;
        counter++;
   }



Here you can see the keyword public. This means that this constructor can be seen and used outside of the Rectangle class, constructors are almost always public. In the first constructor you can see it doesn't take any arguments, and sets both the width and height field to 1.0. The second constructor looks the same as the first but takes two arguments, w and h both of type double. This constructor allows the programmer to specify what they want the width and height of the rectangle object to be the moment the object is made.

   public void setWidth(double w) {
	width = w;
   }



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



Above we have two setter methods, one for width and the other for height. They both perform the same task but on different fields in the class.

   public double getWidth() {
	return width;
   }



   public double getHeight() {
	return height;
   }



Next we have our getter methods, again one for width and the other for height.

   public double getArea(){
      return width * height;
   }



   public double getPerimeter(){
      return (2*width) + (2*height);
   }



Now we have two methods that look similar to a getter method. These methods are used to calculate the area and perimeter of the rectangle object and return the result. Neither the area or perimeter are stored in the rectangle class since both can be found through a calculation.

   public static int getInstances() {
      return counter;
   }



The last method in the class is a static method, again meaning we don't need an instance of the Rectangle class to use the method. To access this method all we have to do is call the name of the Class followed by the name of the method, like this:

Rectangle.getInstances();



Using Objects

Now that we know how to make an object I'm going to demonstrate how to use one. Below is a sample program that creates two instances of the Rectangle class and finds their area and perimeter.


import java.util.*;

public class test {
	
	public static void main(String[] args) {
		double area, perimeter;
		
		//This instance of Rectangle, called rec1, uses the default
		//constructor for our class, thus it sets width and height
		//to 1.0
		Rectangle rec1 = new Rectangle();
		
		//This instance of Rectangle, called rec2, uses the second
		//constructor from our class it sets the width to 2.3 and the
		//height to 1.3
		Rectangle rec2 = new Rectangle(2.3, 1.3);
		
		Scanner keyboard = new Scanner(System.in);
		
		
		//This asks the user to enter a double for the width of rec1
		//and sets rec1's width equal to the input by using the setWidth() method
		System.out.println("Enter the width for rec1:");
		rec1.setWidth(keyboard.nextDouble());
		
		
		//This asks the user to enter a double for the height of rec1
		//and sets rec1's height equal to the input by using the setHeight() method
		System.out.println("Enter the height for rec1:");
		rec1.setHeight(keyboard.nextDouble());
		
		//Now that the width and height have been set in rec1 were going to calculate the area
		//and Perimeter of that Rectangle object.
		area = rec1.getArea();
		perimeter = rec1.getPerimeter();
		
		System.out.println("The area for rec1 is: " + area);
		System.out.println("The pereimeter for rec1 is: " + perimeter);
		
		//We can do the same thing with rec2 and get different results since they are different
		//Rectangle objects and hold different data.
		System.out.println("The area for rec2 is: " + rec2.getArea());
		System.out.println("The pereimeter for rec2 is: " + rec2.getPerimeter());
		
		//Prints out the number of Rectangle instances in the current program.
		System.out.println("There are " + Rectangle.getInstances() + " instances of the Rectangle class.");
	}
}





Output from the program, input was 2 and 3:

Quote

Enter the width for rec1:
2
Enter the height for rec1:
3
The area for rec1 is: 6.0
The pereimeter for rec1 is: 10.0
The area for rec2 is: 2.9899999999999998
The pereimeter for rec2 is: 7.199999999999999
There are 2 instances of the Rectangle class.


Closing Statement
I hope after reading this you have a good foundation of what objects are, how to create your own objects and how to use your own objects efficiently. If you have any questions, comments or concerns feel free to state them in a comment below.

This post has been edited by giggly kisses: 08 July 2011 - 12:02 PM


Is This A Good Question/Topic? 19
  • +

Replies To: How to Create Your Own Objects in Java

#2 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,055
  • Joined: 28-December 10

Posted 05 July 2011 - 08:50 PM

Very comprehensive tutorial! I hate to be pointing this out but I feel "creating" should be "create" on your title... What do you think?
Peace! :)
Was This Post Helpful? 3
  • +
  • -

#3 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 05 July 2011 - 09:03 PM

Thanks a lot good sir! Good catch! I changed the title about 5 times and I didn't realize it still said creating haha. The title used to be "Intro to creating objects in java".
Was This Post Helpful? 0
  • +
  • -

#4 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 05 July 2011 - 09:39 PM

The tutorial has been editing to fit some changes calebjonasson suggested. Thanks for the input. :)
Was This Post Helpful? 0
  • +
  • -

#5 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 971
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Posted 05 July 2011 - 09:46 PM

Very nice!

I have a couple of suggestions:

  • Java methods do not have 'headers'. I would suggest using the term "signature" instead.
  • In your UML diagram both of the constructors are shown as returnng void. Constructors do not return anything.

Was This Post Helpful? 1
  • +
  • -

#6 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 05 July 2011 - 10:17 PM

View Postn8wxs, on 05 July 2011 - 10:46 PM, said:

Very nice!

I have a couple of suggestions:

  • Java methods do not have 'headers'. I would suggest using the term "signature" instead.
  • In your UML diagram both of the constructors are shown as returnng void. Constructors do not return anything.


You sir are 100% correct, I will edit that ASAP. I knew I was going to make a mistake when I made that UML diagram. :sweatdrop: Thank you very much for your input. :)
Was This Post Helpful? 0
  • +
  • -

#7 D.Mulroy  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 81
  • View blog
  • Posts: 430
  • Joined: 30-June 10

Posted 06 July 2011 - 05:11 AM

Great work on the tutorial man :^:
Was This Post Helpful? 0
  • +
  • -

#8 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 943
  • View blog
  • Posts: 2,353
  • Joined: 15-February 11

Posted 06 July 2011 - 05:13 AM

Very good for your first tutorial. In your next you could cover things like polymorphism and inheritance.
Was This Post Helpful? 0
  • +
  • -

#9 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1752
  • View blog
  • Posts: 4,409
  • Joined: 14-March 10

Posted 06 July 2011 - 05:34 AM

Nice tutorial man, keep them coming :)
Was This Post Helpful? 0
  • +
  • -

#10 bmk08  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 11
  • Joined: 28-October 08

Posted 06 July 2011 - 07:39 AM

View Postgiggly kisses, on 05 July 2011 - 07:53 PM, said:

Next we have a getter method with the return type of String. Whenever a method has a return type you must have the keyword return in your method. This keyword must then be followed by a variable or value of the return type (i.e. you can't have a return type of String and try to return an int, it will give you an error).

   public String setField() {
      return field;
   }



Great tutorial! Thanks a lot :)

Just wanted to point out in the above quote I have that I think you meant for that to be GET instead of SET!

    public String getField() {
        return field;
    }


Was This Post Helpful? 1
  • +
  • -

#11 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 06 July 2011 - 10:34 AM

Thank you all for the kind words, much appreciated! Fixed the code snippet, thanks bmk08, good catch! :)

This post has been edited by giggly kisses: 06 July 2011 - 11:45 PM

Was This Post Helpful? 0
  • +
  • -

#12 ducksauce12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-November 10

Posted 07 July 2011 - 08:15 PM

View PostD.Mulroy, on 06 July 2011 - 05:11 AM, said:

Great work on the tutorial man :^:

:^:
Was This Post Helpful? 0
  • +
  • -

#13 javabrijon  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 27-October 09

Posted 11 July 2011 - 05:01 AM

Cool Tut! Might be under the header of "assuming people know a little about Java."

But scope could of been covered i.e instant variables like
private int count;

how its scope covers the whole the class, and a instance method paramater/ variables scope
is only within its method.

What you think?
Was This Post Helpful? 2
  • +
  • -

#14 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Posted 02 August 2011 - 10:22 AM

Great idea, I'll edit the tutorial accordingly. :)
Was This Post Helpful? 0
  • +
  • -

#15 kevinsyel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 15-June 10

Posted 08 November 2011 - 02:50 PM

Hi, I have no experience with Java whatsoever, but I do have programming experience in C++/C# and I felt your tutorial was very beneficial. However, as you covered Constructors before you covered defining the class as:
public class car{
}



I was slightly confused until that portion came up. Maybe a quick explanation of defining the class as such prior to demonstrating default constructors and parameterized constructors would help the instruction flow better.

just my own two cents :)

Otherwise, I agreed with this tutorial very much and was very easy to follow. Kudos!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2