Table of Contents

Java Creating Objects

The object is a basic building block of an OOPs language. An object represents the class and consists of properties and behavior. Properties refer to the fields declared within class and behavior represents the methods available in the class.

public class Student{
   public static void main(String[] args) {
       //creating an object using new keyword  
       Student obj = new Student();  
   }
}
ii) Accessing Class Members:

The object name along with the ( . ) dot operator is used to access members of a class.

syntax:

objectname.variablename;
objectname.methodname(parameter-list);

Example:

public class Student{
     String name = "Anu";
     int mark1 = 50;
     int mark2 = 70;
     int mark3 = 60;
     int total;
     float average;

   void total() {
       total = mark1+mark2+mark3;
       System.out.println("Total:"+total);
   }
   void average() {
       average = total/3;
       System.out.println("Average:"+average);
   }
   public static void main(String[] args) {
       //creating an object using new keyword  
       Student obj = new Student();
       //invoking method using the object
       System.out.println("Name of the student:"+name);
       obj.total();
       obj.average();
   }
}
/*OUTPUT
Name of the student:Anu
Total:180
Average:60.0 */

iii) Accessing class members using multiple objects:

We can also create multiple objects and store information in it through reference variable.

Example:

class Student{
     String name;
     int id;
   }

   class Student1{
   public static void main(String[] args) {
       //creating an object using new keyword  
       Student s1 = new Student();
       Student s2 = new Student();

       //invoking method using the object and dot operator
       s1.name="Riya";
       s1.id = 101;
       s2.name="Anu";
       s2.id = 102;
       System.out.println(s1.id+" "+s1.name);  
       System.out.println(s2.id+" "+s2.name);

   }
}
/*OUTPUT:
101 Riya
102 Anu */

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?