Java Classes and Objects Tutorial

  • Post author:
  • Post category:Java

In this section, we will learn what the class and objects are and how to use them in Java.

Java What is Class?

So far, we’ve worked with primitive data types like `int`, `double`, `float` etc. but in Java, we can build and use our own data type via classes and objects.

Basically, Java is object-oriented programming, and that means we create objects and use those as part of the materials in the program.

But to create an object, we need a plan, a blueprint! This is where classes come in.

Just like in real-world that we use a blueprint to build a house or a car, in Java we use `class` to design the inside and outside of an object and then we use that class to create an object.

You should know that in real-world an object like a Car has attributes like speed, brand, model, weight, color, etc. and it has methods like a pedal, wheel, screen wiper, etc. (that we can use them to run a set of functionality on the car). And all these attributes and methods were first in the blueprint of that car and then implemented when the car was built.

Similarly, in Java programming, we first design a class to set the attributes and methods that we want any object that is created from this class to possess and later on we use the class to build objects from.

How to declare a class in Java? (Defining classes in Java)

Alright, now let’s see the structure of a class and how we can design one: 

Access-specifier class ClassName {

  //body…

}

`access-specifier`: in the access specifier section we will explain in details what it means and how it works but for now just remember that if we don’t set any value here, the class is only accessible within the package that is being declared. So objects can be created from the class if they are in the same package.

`class`: we use the keyword class to signal the compiler that what we’re going to create is actually a class.

`ClassName`: any class should have a name and after the keyword `class` we declare this name. Later in the program, we can call this name to construct an object from it.

Note: by convention, the name of a class should start with a capital letter.

Also, rules that apply to the names of variables also apply to the name of a class.

`{}`: the pair of braces that comes after the name of a class declares the body of that class and this is the place where we declare the attributes (variables) and methods that we want objects of this class to possess.

Example: class in Java

Let’s create a simple class:

public class Person {


    private String name;


    private String lastName;





    public String getName() {


        return name;


    }





    public void setName(String name) {


        this.name = name;


    }





    public String getLastName() {


        return lastName;


    }





    public void setLastName(String lastName) {


        this.lastName = lastName;


    }


}

 

In this example, the name of the class is `Person`, and as you can see, it is prefixed with an access specifier and the keyword `class`.

Within the body of the class, we have two attributes, `name` and `lastName` and 4 methods.

Class in Java Notes:

  • For now, just remember that any attribute (variable) or method in a class that has the `private` access specifier cannot be accessed from objects created of that class. Also, any method or attribute that has the `public` access specifier, can be accessed from objects created of that class.
  • When creating a class, the name of the file that the class is stored in, should be the same as the name of the class. In this example, the name of the class was `Person` and so the file that holds this class should be named `Person` as well.

Remember: Java is case sensitive and so a file name `Person` is different from `person`.

Members of a Class in Java:

It’s like a car. A Car has a few elements or interfaces that we can use to interact with the car. For example, its wheels, pedals, door handles, etc.

These are the public methods and attributes of the car. Basically, things that we see and allowed to interact with are the public attributes and methods of the car (also we say these are the interface of the car).

On the other hand, there are hundreds of materials under the hood of the car, like its sensors and engines and the materials inside the engine that we can’t and shouldn’t interact with those materials directly.

So these pieces of stuff (things that are hidden from us) are considered as the `private` attributes and methods of the car.

In this example, both `name` and `lastName` attributes are private and so no objects can access these two attributes (variables).

On the other hand, 4 methods of this class `getName()`, `setName()`, `getLastName()`, `setLastName()` are declared as `public` and so any object created of this class can access these methods. These are basically the interface of the objects created from this class (things that we are allowed to interact with when we have an object).

Java What is Object?

Object is the representation of a class that practically can be interacted with in a program. You should know that classes on their own are just blueprint and we can’t run a program with just classes. It’s the objects that represent interactive components in Java programs.

The `new` keyword and object creation in Java

To create an instance (AKA object) from a class, we use the `new` keyword as the example below shows:

new ClassName();

`new` keyword: the keyword `new` is used to create an object.

`ClassName`: we use the name of a class that we want to create an object form and this name comes after the keyword `new`.

`()`: by default we put a pair of empty parentheses after the name of the class that the object is going to be created from.

Note: in constructor section we explained more on how and why non-empty parentheses are used in object creation.

`;`: creating an object is a statement and just like other statements, we end this statement via a semicolon `;`.

When we create and object, this object will be stored in the memory. But now we need a way to refer and access that object!

This is where we declare a variable of the same class type that the object was created from and store a reference of the object into that variable.

Example:

ClassName var = new ClassName();

Here, as you can see, the variable `var` is the one that holds the reference of the object and via this variable, we can access the public members (attributes and methods) of the object.

Example: creating objects in Java

Alright now let’s run an example to see the creation of an object in practice:

In your IDE create a class named `Start` and copy the code below into that class:

public class Start {
    private String name;
    private String lastName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

 

Now create another class named `Simple` and copy the code below into that class as well:

public class Simple {
    public static void main(String[] args) {
        Start st = new Start();
        st.setName("John");
        st.setLastName("Doe");
        System.out.println(st.getName());
        System.out.println(st.getLastName());
    }
}

 

Output:

John

Doe

Java Creating Object Notes:

  • The object that is created from a class is stored in a memory location. The variable that we used to access the object only holds the memory address of that object. Later on in the program, we use this variable (its address) to access the members of the target object.
  • When we create an object from a class, any member of that class will be copied to a new memory location that is allocated to the object. This means any object of that class has its own copy of the members and changing one attribute of an object won’t change the same attribute of another one.
  • Other than the `new` keyword, there are other methods by which we can create an object from a class in Java. You’ll learn about them in later sections.
  • When creating a class, the name of the file that the class is stored in should be the same as the name of the class. In this example, the name of one class was `Start` and so the file that holds this class should be named `Start` as well. Another class in this example is named `Simple` and so its file name should also be `Simple`.

Remember: Java is case sensitive and a file name `simple` is different from `Simple`.

  • A Java program should have a method named `main` exactly like the one we’ve declared in the `Simple` class.
  • When a Java program runs, the execution starts with the `main` method. Basically the computer will look for this method and start the execution from there.
  • If you’re using package in your IDE, make sure both files are in the same package.

Alright, as you can see, here we’ve created an object of type `Start` and stored the reference of that object in the variable named `st` which is of the same type.

Now this variable represents the object and we can use it to access the public members of the object.

How to access Members of an Object?

To access the public members of an object, we can use the dot `.` operator.

For example, if we want to access the `setName()` method of the `st` object, we use the name of the object (in this case `st`) followed by that is the dot `.` operator and then the name of the public member (in this case `setName()`).

So the `st.setName()` gave us the access to the `setName()` method of this object.

We also used other public members of the `st` object like:

st.setLastName();

st.getName();

st.getLastName();

Note: for now, don’t worry about why we used parentheses after the name of a method or why some of the methods took arguments and some of them didn’t. These are covered in the Java method section.

In this section, we’re just trying to show you how we can create an object and what members are accessible and what not as well as how we can access a public member of an object.

Multiple Objects

In Java, when you have a class, there’s no limit on how many objects you’re allowed to create from that class!

Basically, you can create as many objects from the same class as you want. These instances will be independent from each other! (They’ll have their own copy of the members in the class).

Example: creating multiple objects from a class

import java.util.Arrays;
class Main{
    private String name; 
    private String lastName;
    public Main(String name, String lastName){
        this.name = name; 
        this.lastName = lastName; 
    }
    public static void main(String[] args) {
        Main main1 = new Main("Omid","Dehghan");
        Main main2 = new Main("John","Doe");
        Main main3 = new Main("Elon","Musk");

        System.out.println(main1.getName()+ " "+ main1.getLastName());
        System.out.println(main2.getName()+ " "+ main2.getLastName());
        System.out.println(main3.getName()+ " "+ main3.getLastName());
    }
    public String getName(){
        return name;
    }
    public String getLastName(){
        return lastName;
    }
    public void setName(String name){
        this.name= name;
    }
    public void setLastName(String lastName){
        this.lastName = lastName;
    }
}

Output:

Omid Dehghan

John Doe

Elon Musk

 

As you can see, here we’ve created 3 objects (instances) of the `Main` class.

Note: again, don’t worry about the members we’ve defined in the body of this class for now! In later sections, you’ll learn the entire members of a class in great details.

Difference between Class and Object in Java: Class vs Object

As mentioned before, a class is basically a blueprint, a sketch of a tool we want might want to have in a program!

On the other hand, objects represent the actual tools, the instance or the built version of a class that practically can be used in a program!

More to Read:

Java Class Fields

Java Class Methods

Java Class Constructors

Java Interfaces

Java Nested Class

Java Anonymous class

Leave a Reply