Close
Close

Java Classes and Objects


We discussed the concept of classes and objects in the previous chapter. Before learning to create classes and objects using Java, let’s see one more example.

We know that a student has a name and a roll number. So, we can say that Student is a class, and name and roll number are the attributes of this class. Furthermore, we know that there can be many students and each student will have a name and a roll number. Thus, all students are the objects of the Student class.

So, you must have understood the basic concept of classes and objects. Now, let’s see how to create a class and its objects.


Creating Classes and Objects in Java

A class is created using the class keyword.

class Student {

    String name;
    int roll_no;
}

In the above declaration, Student is the name of a class. In other words, Student is a class.

In the body of the class, the attributes name and roll_no are defined.

So, we can say that each student has a name and a roll number.

Attributes are variables defined inside a class.

Now let’s create an object of this class.

// Student class
class Student {

    String name;
    int roll_no;
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating object st of class Student
        Student st = new Student();
    }
}

In the above example, Test is the main class containing the main method.

The class which has the main method inside it is known as the main class. Till now we were writing all our code in the main class.

We created the Student class having two attributes - name and roll_no.

Student st = new Student() → We created an object st of the Student class. We can also say that st is a Student.

The terms object and instance are used interchangeably.

Any number of objects of a class can be created.

// Student class
class Student {

    String name;
    int roll_no;
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating objects st1 and st2 of class Student
        Student st1 = new Student();
        Student st2 = new Student();
    }
}

Here, we created two objects of the Student class - st1 and st2. Thus, st1 and st2 are two Students having some name and roll number.

You now know how to create a class with attributes and its objects. Now let’s move forward and assign values to attributes.


Java Attributes

We know that attributes are variables defined in a class. They specify the features (properties) of the class. For example, name and roll_no are the attributes/features of the Student class.

// Student class
class Student {

    String name = "John";
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating object st of class Student
        Student st = new Student();
        System.out.println(st.name);
    }
}
Output
John

In this example, a class named Student is defined. It has an attribute name having the value “John”.

Student st = new Student() → An object st of the Student class is created.

System.out.println(st.name) → The object st accesses the attribute name of the class through st.name and its value is printed.

Note that an object of a class can access the attributes of that class using the dot ‘.’ operator. In the above example, the object st accesses the attribute name of the Student class through st.name.

accessing methods using dot (.) in Java

In the above example, we can say that st is a Student whose name is “John”.

Let’s see another way to assign value to attributes.

// Student class
class Student {

    String name;
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating object st of class Student
        Student st = new Student();

        // assigning value to attribute name
        st.name = "John";

        System.out.println(st.name);
    }
}
Output
John

Here, the statement st.name = "John" assigned the value of the attribute name for the object st to “John”.

Look at another example.

// Student class
class Student {

    String name = "John";
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating objects st1 and st2 of class Student
        Student st1 = new Student();
        Student st2 = new Student();
        System.out.println("Student 1 Name: " + st1.name);
        System.out.println("Student 2 Name: " + st2.name);
    }
}
Output
Student 1 Name: John
Student 2 Name: John

Two objects st1 and st2 of the Student class are created. These objects accessed the value of the attribute name through st1.name and st2.name respectively.

Thus, st1 and st2 are two Students having the same name i.e. “John”.

Now in the above example, we can define different names for both the objects as shown below.

// Student class
class Student {

    String name;
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating objects of class Student
        Student st1 = new Student();
        Student st2 = new Student();

        // assigning values to attribute name for objects
        st1.name = "John";
        st2.name = "Julie";

        System.out.println("Student 1 Name: " + st1.name);
        System.out.println("Student 2 Name: " + st2.name);
    }
}
Output
Student 1 Name: John
Student 2 Name: Julie

The statement st1.name = "John" assigned the value of the attribute name for the object st1 as “John” and the statement st2.name = "John" assigned the value of the attribute name for the object st2 as “Julie”.

Thus, st1 is a Student having the name “John” and st2 is also a Student having the name “Julie”.

If you have understood till here, the rest of the topic will be an easy walk for you. Let’s move further.


Java Methods in Class

In the above examples, we defined variables (known as attributes) in a class. Similarly, we can also define methods in a class. The variables and methods defined in a class are called members of the class.

Let’s define a method in our Student class.

// Student class
class Student {

    String name = "John";

    void description() {
        System.out.println("This is a student");
    }
}

// Test (Main) class
class Test {

    public static void main(String[] args) {
        // creating object st of class Student
        Student st = new Student();

        // accessing variable name of class
        System.out.println(st.name);

        // accessing method description of class
        st.description();
    }
}
Output
John
This is a student

In this example, the Student class has a variable (attribute) name and a method description() defined in it. This variable and method are the members of the class.

We created an object st of this class. Thus, the object accessed the class attribute by writing st.name and the class method by writing st.description().

Now let’s look at another example.

class Student {

    String name;

    void setName(String n) {
        name = n;
    }

    String getName() {
        return name;
    }
}

class Test {

    public static void main(String[] args) {
        Student st = new Student();

        st.setName("John");
        String st_name = st.getName();
        System.out.println("Student Name: " + st_name);
    }
}
Output
Student Name: John

We created the Student class having an attribute name and methods getName() and setName().

Student st = new Student() → An object st of the class is created.

st.setName("John") → The object st calls the method setName() by passing “John” to it. Inside the setName() method, name = n assigns “John” to the variable name.

String st_name = st.getName() → The object st calls the method getName(). Inside the getName() method, return name returns the value of the variable name i.e. “John”. Thus, the value of the variable st_name becomes “John”.

By now, you know how to create classes and its objects. You also know that variables and methods can be defined in a class and can be accessed by the objects of that class. Pretty simple uptil here, right?

Now let’s move onto the next concept.


Java Constructor

A constructor is a special class method which gets called automatically whenever an object of the class is created. Its name is the same as the class name and it has no return type.

Constructor is a special type of method which is used to initialize an object. It is invoked at the time of object creation.

Since the constructor is called at the time of object creation, the part of the code that you want to execute at the time of object creation should be written in it.

An example will help understand the use of a constructor.

class Student {

    String name;

    // constructor
    Student() {
        name = "Unknown";
    }

    void setName(String n) {
        name = n;
    }

    String getName() {
        return name;
    }
}

class Test {

    public static void main(String[] args) {
        // creating object st of Student class
        Student st = new Student();

        // printing value of name of st
        System.out.println("Student Name: " + st.getName());

        // changing value of name of st
        st.setName("John");

        // printing value of name of st
        System.out.println("Student Name: " + st.getName());
    }
}
Output
Student Name: Unknown
Student Name: John

In this example, the Student class is defined with an attribute name, a constructor Student() and two methods getName() (returns the value of name) and setName() (assigns a value to name).

When we created the object st of the class Student, the constructor Student() automatically got called. Inside the constructor, the value of the attribute name is initialized to “Unknown”. Therefore, on printing the value of st.getName() after that, “Unknown” got printed.

Next, st.setName("John") called the setName() method to set the value of name to “John”. Thus, on printing the value of st.getName() after that, “John” got printed.

Therefore, in the above example, we are assigning the name of the objects as “Unknown” by default using the constructor.

Let’s see another example.

class Student {

    String name;
    int age;

    // constructor
    Student() {
        name = "Unknown";
        age = 0;
    }

    void setDetails(String n, int a) {
        name = n;
        age = a;
    }

    void printDetails() {
        System.out.println("My name is " + name + " and my age is " + age);
    }
}

class Test {

    public static void main(String[] args) {
        Student st1 = new Student();
        Student st2 = new Student();

        st1.setDetails("John", 25);
        st2.setDetails("Julie", 20);

        st1.printDetails();
        st2.printDetails();
    }
}
Output
My name is John and my age is 25
My name is Julie and my age is 20

You must have understood this program. When the objects st1 and st2 were created, the constructor Student() got called and assigned name as “Unknown” and age as 0 for both the objects. After that, both the objects called the setDetails() method to set the respective values of name and age and the printDetails() method to print their values.

We can also make a constructor with nothing in its body.

Student(){ };

If we don’t explicitly create any constructor in a class, then the compiler automatically creates a constructor with no parameter and empty body.

Java Constructor Having Parameters

We can also define constructors having parameters.

class Student {

    String name;
    int age;

    // constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }

    void printDetails() {
        System.out.println("My name is " + name + " and my age is " + age);
    }
}

class Test {

    public static void main(String[] args) {
        Student st1 = new Student("John", 25);
        Student st2 = new Student("Julie", 20);

        st1.printDetails();
        st2.printDetails();
    }
}
Output
My name is John and my age is 25
My name is Julie and my age is 20

Here, the constructor Student() has two parameters, the first parameter of type String and the second parameter of type int. Therefore, when creating an object of the Student class, we have to pass two arguments.

Look at the following statement.

Student st1 = new Student("John", 25);

This statement creates an object st1 and calls the Student() constructor by assigning the value “John” to n and 25 to a. In the constructor, n (“John”) is assigned to name and a (25) is assigned to age. The same is done for the object st2 also.

Using public and private Modifiers

We will discuss modifiers in the chapter Access Modifiers. Let's just learn about a few things which are necessary for now. Members (variables and methods) of a class are usually declared as private or public.

Declaring a class variable/method as private means that the variable/method can be accessed only inside the class. Accessing a private variable/method outside the class will result in an error. Whereas, declaring a class variable/method as public means that the variable/method can be accessed outside the class in which it is defined.

Therefore, we can’t access a private variable/method through the class object outside the class.

Usually, class variables (attributes) are declared private and class methods are declared public. (We will learn about the reason for doing so in the Encapsulation chapter)

Let’s make all class variables as private and class methods as public in the last example.

class Student {

    private String name;
    private int age;

    // constructor
    public Student(String n, int a) {
        name = n;
        age = a;
    }

    public void printDetails() {
        System.out.println("My name is " + name + " and my age is " + age);
    }
}

class Test {

    public static void main(String[] args) {
        Student st1 = new Student("John", 25);
        st1.printDetails();
    }
}
Output
My name is John and my age is 25

In this example, the object st1 was able to access the method printDetails() because this method is declared as public.

Now let’s try to access a private attribute outside the class in the above example.

class Student {

    private String name;
    private int age;

    // constructor
    public Student(String n, int a) {
        name = n;
        age = a;
    }

    public void printDetails() {
        System.out.println("My name is " + name + " and my age is " + age);
    }
}

class Test {

    public static void main(String[] args) {
        Student st1 = new Student("John", 25);
        System.out.println(st1.name);
    }
}
Output
Test.java:19: error: name has private access in Student
        System.out.println(st1.name);                                 ^
1 error

We got an error. This is because the object st1 tried to access the private attribute name outside the Student class.

From now on, let’s make a habit of declaring class attributes as private and class methods as public in normal conditions. In the rest of the examples, we will follow this pattern.

Let’s see another example.

class Rectangle {

    private int length;
    private int breadth;

    public Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }

    public int getArea() {
        return length * breadth;
    }
}

class Test {

    public static void main(String[] args) {
        Rectangle rect = new Rectangle(2, 4);
        System.out.println(rect.getArea());
    }
}
Output
8

This program has a class named Rectangle which has length and breadth as attributes and a method getArea() that returns the area of the rectangle. Try to understand the rest of the code yourself.


Java static

Declaring a variable/method defined in a class as static means that the variable/method can be accessed without making an object of the class in which it is defined. In other words, static is used so that we can access any variable or method in a class without making an object of that class.

Let's understand with an example.

class Rectangle {

    public static void printArea(int l, int b) {
        System.out.println(l * b);
    }
}

class Test {

    public static void main(String[] args) {
        Rectangle.printArea(2, 4);
    }
}

Here, the method printArea() is declared as static. As a result, we were able to access it by directly using the class name Rectangle, without creating an object of the class.

Now let’s get to the last topic of this chapter.


Returning and passing object in a method

Yes, we can return or pass object(s) to a method.

Let’s see how.

class Account {

    public int balance;

    public Account() {
        balance = 0;
    }

    public static Account getAcc(Account a, Account b) {
        Account ac = new Account();
        ac.balance = a.balance + b.balance;
        return ac;
    }
}

class Test {

    public static void main(String[] args) {
        Account a1 = new Account();
        a1.balance = 50;

        Account a2 = new Account();
        a2.balance = 60;

        Account a3 = Account.getAcc(a1, a2);
        System.out.println(a3.balance);
    }
}
Output
110

In this example, the getAcc() method is taking two Account objects as parameters and returning an Account object. Note that the attribute balance is defined as public because we want the objects to directly access this attribute in this example.

Account a3 = Account.getAcc(a1, a2);

In the above statement, the getAcc() method is taking the objects a1 and a2 and is returning a new object of the Account class. The returned object is assigned to a3.

public static Account getAcc(Account a, Account b) {
    Account ac = new Account();
    ac.balance = a.balance + b.balance;
    return ac;
}

Inside the getAcc method, a new object ac is created. Then the sum of balances of the two parameter objects is assigned to the balance of ac, and finally ac is returned.

So this completes the topic - classes and objects. If you have understood this chapter, then you have surpassed many beginners who find it difficult.

This might be a heavy chapter, so go through it thoroughly and ask doubts in the discussion forum. Also practice questions on classes and objects from the practice section before moving onto the next chapter.

If You Are Working On Something That You Really Care About, You Don’t Have To Be Pushed. The Vision Pulls You.
- Steve Jobs


Ask Yours
Post Yours
Doubt? Ask question