Sage-Code Laboratory
index<--

Java Objects

Java is an object-oriented language and not a procedural or functional language. It is also an imperative language. Therefore we have to understand how objects are created and what object-oriented means.

This topic is pretty much the base of all Java programming. Which is why this post will have to be longer than the other posts to fully explain this concept.

Example of a class:

//This is a class method, notice that it has no main method
//We use this class in the tester one bellow
public class MyPoint
{
 private int x;//instance variables
 private int y;
 public MyPoint()//no-arg cst
 {
 this.x = 0;
 this.y = 0;
 }
 public MyPoint(int x, int y)
 {
 this.x = x;
 this.y = y;
 }
 //getter method, with int return type
 public int getX()
 {
 return this.x;
 }
 public int getY()
 {
 return this.y;
 }
 //sets the instance variables
 public void setXY(int x, int y)
 {
 this.x = x;
 this.y = y;
 }
 public String toString()
 {
 return String.format("(" + this.x + "," + this.y + ")");
 }
 //This operation finds the distance between the specified point
 //and the objects current point
 public double distance(int x, int y)
 {
 return Math.sqrt(Math.pow(this.x - x, 2) + (Math.pow(this.y - y, 2)));
 }
 //this actually passes in an object as a parameter
 //Therefore we must use the getters to retrieve X and Y
 public double distance(MyPoint pt)
 {
 return Math.sqrt(Math.pow(pt.getX() - this.x, 2) + (Math.pow(pt.getY() - this.y, 2)));
 }
}

Ussing a class:

public class MyPointTest
{
 public static void main(String[] args)
 {
 //this invokes our first contructor
 MyPoint p1 = new MyPoint();
 //this invokes our second constructor
 MyPoint p2 = new MyPoint(4, 8);
 double dis = p1.distance(3, 4);
 System.out.print("The distance from " + p1.toString());
 System.out.println(" to (3, 4) is: " + dis);
 p1.setXY(10, 10);
 System.out.println("x is: " + p1.getX());
 System.out.println("y is: " + p1.getY());
 MyPoint[] points = { p1, p2, new MyPoint(7, 3) };
 for (int i = 0; i < points.length - 1; i++)
 {
 System.out.print("The distance from " + points[i].toString());
 System.out.print(" to " + points[i + 1].toString() + " is: ");
 dis = points[i].distance(points[i + 1]);
 System.out.println(dis);
 }
 }
}

The way Objects/Classes work

Instance Variables

Constructor

Accessor modifiers/Encapsulation

This keyword

this is a keyword that represents the object, which indicates the compiler to use the method on the objects values.

If a movie with the tittle "The Matrix" uses the method getTitle(), this method has the following code:

public String getTitle()
{
 return this.title;
}

this.title will refer to the title of the movie that is calling the method.

This explains for short how to declare a class and use the class to create an object.


Read next: Strings