Classes and Objects in Java with examples

As we know Java is an Object Oriented Programming language, and according to this programming paradigm, everything in the language is represented in terms of Objects. But the Objects themselves cannot exist without another entity, which is known as a Class. Objects and Classes both are the core concepts of Object Oriented Programming(OOPs). In this tutorial, we'll study about them in detail.


Classes in Java

In Java programming, a class is considered as a template for creating objects or you can say a user-defined blueprint for the objects. It tells us about the attributes that the object possess and the methods/functions it can perform/call.


creating a class in Java

class className {
//attributes
//methods
}

Example: 

class Student {

/* attributes */
public int rollNum;
private char section;
String name;

/* Methods */
public void wakeUpEarly(){
System.out.println("Wake up at 7am");
}

public void goToSchool(){
System.out.println("Wake up at 7am");
}

}

* By convention, the class-name, should have the first alphabet capital, like 'Student' as mentioned in the above example.
* Attributes represent the characteristics that the object of that class would have. Like in this example; every object of the class Student would have its unique rollNum, section and name. 
These attributes mentioned in the class are known as instance variables, they represent the state of the object.
You can also specify the access modifier along with the instance variables for limiting their scope and also to achieve abstraction.
If no access-modifier is specified, then the default access modifier is used.
Methods in the class represent the behaviour of the objects or what the objects can do.
The Java methods can also be specified along with access modifiers like default, public, private and protected.

Inside a class, you can also specify other class, interfaces and constructors. When a class is put inside another class, then this is known as nesting of classes

* We can have only 1 public class in Java, and this public class should contain the main() method.

Objects in Java

Objects are the basic unit of an Object Oriented programming language and they are used to represent real-world entities. As every thing around us, like the table, chair and computer is an object having a particular state and property. 

Objects are also known as instances of class. For example, Fiat is an instance of a class Car. 

> Creating an Object

Objects are created or instantiated using the new keyword. The new keyword dynamically allocates memory(at runtime) for an object and returns reference to it. And this reference, is the address of memory of the object allocated by new. This memory is allocated in Heap memory.

Syntax:

class-name object-name = new class-name(); 
or
class-name object;
object = new class-name();
         

To access the instance variables of class, the dot(.) operator is used. It links the name of the object with the name of the instance variable. For example, to assign the rollNum variable of Student class object s1, value of 10, we'll say

s1.rollNum = 10;

It will assign rollNum with a value of 10 for the object s1. We can also call a particular method of the class using dot operator.

Example: 

with main() inside the class - 

public class Class1{
    int x=9;
    void printMethod(){
    System.out.println("Hello");
    }
    public static void main(String args[]){
    Class1 obj1 = new Class1();
    System.out.println(obj1.x);
    Class1.printMethod();
    }
    }

OUTPUT 

9
Hello

* When the methods are in the same class, then you can call the method without using the reference variable. You just need to write the class-name then the dot operator and then method-name.
Class1.printMethod();

with main() inside another class -

class Drive{
    String status = "Driving";
    }
    public class testDrive{
    public static void main(String args[]){
    Drive ob1 = new Drive();
    System.out.println(ob1.status);
    }
    }

OUTPUT

Driving

>> Creating Multiple objects

Example: 

class myClass{
    System.out.println("Hello");
    }
    class testMyClass{
    public static void main(String[] args){
    myClass ob1 = new myClass(), ob2 = new myClass();
    }
    }

> Initializing an Object

Objects can be initialized by using reference or by using constructors or by using methods

>> Using references is the easiest for beginners.

Example:
public class Class1{
    int x;
    public static void main(String args[]){
    Class1 obj1 = new Class1();
    obj1.x = 10;
    System.out.println(obj1.x);
    }
    }

OUTPUT 

10

>> initializing an object using constructors

class MyClass1{
    int age;
    String name;
    
    void setName(String name){
    this.name=name;
    }
    
    void setAge(int age){
    this.age=age;
    }
    
    String getName(){
    return this.name;
    }
    
    int getAge(){
    return this.age;
    }
    }
    public class mainClass{
    MyClass1 ob1 = new MyClass1();
    ob1.setName("ABC");
    ob1.setAge(10);
    System.out.println(ob1.getName() + " " + ob1.getAge());
    }

OUTPUT

ABC 10

* The methods used for setting the values of the instance variables are also known as setters, whereas the ones which give us the values back are getters. This concept of getters & setters is also quite popular amongst OOPs programmers.

>> Initializing object using constructors

class MyClass1{
    int age;
    String name;
    
    MyClass1(String name, int age){
    this.name=name;
    this.age=age;
    }
    
    String getName(){
    return this.name;
    }
    
    int getAge(){
    return this.age;
    }
    }
    public class mainClass{
    MyClass1 ob1 = new MyClass1("ABC",10);
    System.out.println(ob1.getName() + " " + ob1.getAge());
    }

OUTPUT

ABC 10

FAQs


Ques 1. What are constructors in java?
Ans. Constructors are special type of methods that are used to initialize objects immediately upon creation. Constructors can be parameterized or with no parameters.

Ques 2. What is this keyword in java?
Ans. this keyword is used to refer to the current object. It is reference to the object on which the method is called.

Ques 3. What are access modifiers in java?
Ans. These are keywords that define the access level for classes, attributes, methods and constructors. There are 4 access-modifiers in Java: default, public, private and protected.

Ques 4. What is an interface in java?
Ans. Interface is an abstract class used to group related methods with empty bodies. We can also fully abstract a class' interface using the interface keyword. It can specify what a class must do, without specifying how it does it.

Ques 5. What are getters and setters in java?
Ans. These are 2 conventional methods used to set the values of instance variables and retrieving them for an object. They provide protection to the data, i.e, abstraction. The getter method returns the value, whereas setter sets of updates the value.

Ques 6. What are nested classes in Java?
Ans. Classes are said to be nested, when one class is defined in another class.

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post