Part 8-java class and objects.





Objects


Everything in Java is within classes and objects. Java objects hold a state, state are variables which are saved together within an object, we call them fields or member variables.
Let start with an example:
class Point {
    int x;
    int y;
}
This class defined a point with x and y values.
In order to create an instance of this class, we need to use the keyword new.
Point p = new Point();
In this case, we used a default constructor (constructor that doesn't get arguments) to create a Point. All classes that don't explicitly define a constructor has a default constructor that does nothing.
We can define our own constructor:
class Point {
    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
This means we can not longer use the default constructor new Point(). We can now only use the defined constructor new Point(4, 1).
We can define more than one constructor, so Point can be created in several ways. Let's define the default constructor again.
class Point {
    int x;
    int y;

    Point() {
        this(0, 0);
    }

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
Notice the usage of the this keyword here. We can use it within a constructor to call a different constructor (in order to avoid code duplication). It can only be the first line within the constructor.
We also used the this keyword as a reference of the current object we are running on.
After we defined p we can access x and y.
p.x = 3;
p.y = 6;
Powered by Blogger.