Class and Object in Java

In this tutorial, we will learn about Class and Object in Java. We are using the class keyword from our very first tutorial of this series. As we learned in previous tutorials Java is an Object-Oriented programming language. It means we can not write anything(variables and methods) outside the scope of the class.

Class is a blueprint for an object. For example, you have object student we can create a class for student object which can have variables like stu_name, stu_class and methods etc;

Creating a class:

It’s so easy to create a class in Java. we have a class keyword. Write this class keyword then write the class name and in brackets write method constructors and variable of the array. Check this simple class example.

class Student{
    string stu_name;
    int stu_marks;
    
    public void show(){
     System.out.println(stu_name+" "+stu_marks);
    }
}

Object in Java:

The object is also known as Real-life entity. The object is something that uses the class. Here we will learn how we can create an object for our class and how we call the method of our class using that object.

Syntax to create Object in Java:

className  referenceVariable = new ConstructorOfClass();

In the following example, you can see the syntax to create an object of the class. In the given illustration you can clearly see obj is not an object of the class(Some student always think that obj is an object.) it is just a reference variable which is referring to an Object. Here new and Constructor together create a new object of the class.

Example Program:

class Student{
    string stu_name;
    int stu_marks;
    
    public void setData(String name,int marks){
      stu_name=name;
      stu_marks=marks;
    }

    public void show(){
     System.out.println(stu_name+" "+stu_marks);
    }
}

class ObjectExample{
   public static void main(String args[]){
     Student obj=new Student();
     obj.setData("Ravi",30);
     obj.show();
   }
}

Anonymous Object:

When we create an object of class without a reference variable this kind of object known as anonymous object. It is important to not this kind of can be use only once.

Example Program:

class Greetings{
    public void hello(String name){
      System.out.println("Hello "+name)
    }
}

class ObjectExample{
   public static void main(String args[]){
     new Greetings().hello("Owlbuddy");
     new Greetings().hello("Java");
     new Greetings().hello("Python");
   }
}

 

Spread the love
Scroll to Top