Java Class and Object

In Java, a class is a blueprint or template for creating objects. It defines the structure and behavior of objects of that class. An object, on the other hand, is an instance of a class. It represents a real-world entity or concept and can be created based on the class’s blueprint. Here are the key concepts related to Java classes and objects:

Class & Object

  1. Class:
    • A class is a user-defined data type in Java.It serves as a blueprint for creating objects.Classes define attributes (fields or variables) and methods (functions) that can be used to manipulate those attributes.Class members can have access modifiers like public, private, protected, or default to control their visibility and accessibility.

Class Syntex

access modifier class ClassName
{
  access modifier field1;
  ------------------------------
  ------------------------------
  acess modifier method1;
  ------------------------------
  ------------------------------
 }
//Note: In C++, We can use specifier in place of modifier.

Example of a simple Java class:

public class Car {
    // Fields
    String make;
    String model;
    int year;

    // Constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Method
    public void start() {
        System.out.println("The " + year + " " + make + " " + model + " is starting.");
    }
}

Object:

  • An object is an instance of a class, created using the new keyword.
  • Objects have attributes and behaviors defined in the class.
  • Multiple objects can be created from the same class, each with its own set of attribute values.

Example of creating objects from the Car class:

public class Main {
    public static void main(String[] args) {
        // Creating Car objects
        Car car1 = new Car("Toyota", "Camry", 2023);
        Car car2 = new Car("Honda", "Accord", 2022);

        // Accessing object attributes and invoking methods
        System.out.println("Car 1: " + car1.make + " " + car1.model + " " + car1.year);
        car1.start();

        System.out.println("Car 2: " + car2.make + " " + car2.model + " " + car2.year);
        car2.start();
    }
}

In this example, we defined a Car class with attributes (make, model, year) and a start method. We then created two Car objects (car1 and car2) and used them to access attributes and invoke methods.

Classes and objects are fundamental concepts in object-oriented programming (OOP) and are used to model real-world entities and encapsulate their data and behavior.

Difference b/w Java Class & Obect

AspectJava ClassObject
DefinitionA class is a blueprint or template for creating objects.An object is an instance of a class, created based on the class’s blueprint.
UsageClasses are used to define the structure and behavior of objects.Objects are used to represent real-world entities and instances of classes.
AttributesClasses define attributes (fields/variables) and methods (functions).Objects have values for the attributes defined in the class.
CreationClasses are not created at runtime; they are used to create objects.Objects are created at runtime using the new keyword.
ExamplesIn code, classes are written using the class keyword.In code, objects are created using the new keyword followed by the class name.
Multiple InstancesMultiple objects can be created from the same class, each with its own set of attribute values.Each object is a distinct instance with its own attribute values.
InheritanceClasses can inherit attributes and methods from other classes through inheritance.Objects do not inherit attributes or methods; inheritance applies at the class level.
BehaviorClasses define what objects can do by specifying their methods.Objects represent instances with actual data and can execute methods defined in the class.
MemoryClasses do not consume memory during program execution; they exist only at the source code level.Objects consume memory in the runtime, as they store their data and state.
RelationshipsClasses can have relationships with other classes (e.g., associations, dependencies).Objects can have relationships with other objects and interact with them.

Access Modifier

  • Private
  • Public (treated as default)
  • Protected
  • Default/Friendly (Here is default is only name don’t behaves like default–mindit)
    • This is not keyword. it is considered when no access modifier is specified.
    • it is also known as “Package Level Access”.

Note: For understanding, class is treated as file & package is treated as folder.

Example of class with private access modifier

//Example of class with private access modifier
class DemoFirst
{
	private int x,y;
	void input (int a, int b)
	{
	    x=a;
	    y=b;
	}
	public void show()
	{
	    System.out.println("x is "+x+"\n y is "+y);
	}
	void sum()
	{
	    int s;
	    s=x+y;
	    System.out.println("Sum is "+s);
	}
}
public class Main
{
    public static void main(String args[])
    {
        DemoFirst df = new DemoFirst();
        df.input(50,70);
        df.show();
        df.sum();
    }
}

class example with public access modifier

//class example with public access modifier
class DemoFirst
{
    public int x,y;
}
public class Main
{
    public static void main(String args[])
    {
        DemoFirst f = new DemoFirst();
        f.x=10;
        f.y=25;
        System.out.println(f.x);
        System.out.println(f.y);
        System.out.println(f.x+f.y);
    }
}

class example with protected access modifier

//class example with protected access modifier
class DemoFirst
{
    protected int x,y;
}
public class Main
{
    public static void main(String args[])
    {
        DemoFirst f = new DemoFirst();
        f.x=10;
        f.y=25;
        System.out.println(f.x);
        System.out.println(f.y);
        System.out.println(f.x+f.y);
    }
}

class example with default/friendly access modifier

//class example with default/friendly access modifier
class DemoFirst
{
    int x,y;
}
public class Main
{
    public static void main(String args[])
    {
        DemoFirst f = new DemoFirst();
        f.x=10;
        f.y=25;
        System.out.println(f.x);
        System.out.println(f.y);
        System.out.println(f.x+f.y);
    }
}

Array of Object in Java

//Prog. to store & display 3 employee details from array of object
import java.util.Scanner;
class Employee
{
    private String name, address;
    private int eid, salary;
    void input()
    {
        Scanner obj = new Scanner(System.in);
        System.out.print("Enter name: ");
        name = obj.nextLine();
        System.out.print("Enter id: ");
        eid = obj.nextInt();
        obj = new Scanner(System.in);     //Creating fresh object (i.e. in c++ use fflush(stdin) )
        System.out.print("Enter address: ");
        address = obj.nextLine();
        System.out.print("Enter salary: ");
        salary = obj.nextInt();
    }
    void show()
    {
        System.out.println("Name is "+name);
        System.out.println("id is "+eid);
        System.out.println("Address is "+address);
        System.out.println("Salary is "+salary);
    }
}
public class Main 
{
    public static void main(String args[])
    {
        Employee e[] = new Employee[5];
        for(int i=0; i<e.length; i++)
        {
            e[i] = new Employee();
        }
        System.out.println("Enter details of 5 employee: ");
        for(int i=0; i<e.length; i++)
        {
            e[i].input();
        }
        System.out.println("All employee details -----");
        for(int i=0; i<e.length; i++)
        {
            e[i].show();
        }
    }
}

Output

Enter details of 3 employee:
Enter name: Harsh
Enter id: 87
Enter address: Delhi
Enter salary: 15000
Enter name: Raju
Enter id: 34
Enter address: Patna
Enter salary: 8000
Enter name: Gopal
Enter id: 89
Enter address: up
Enter salary: 8000
All employee details —–
Name is Harsh
id is 87
Address is Delhi
Salary is 15000
Name is Raju
id is 34
Address is Patna
Salary is 8000
Name is Gopal
id is 89
Address is up
Salary is 8000

Passing Parameter in Java

  • Call by Value
    • (But both Call by Value & Call by Reference behaviour is seen based on data).

Note: In Java, For Value(or Perimitive) type Call by value behaviour is seen while for reference type call by reference is seen.

Passing Object as argument (format like x= x + y)

//Passing Object as argument (x=x+y)
class Complex
{
    private int real, imag;
    void input(int r, int im)
    {
        real = r;
        imag = im;
    }
    void show()
    {
        System.out.println(real+"+"+imag+"i");
    }
    void add(Complex c)
    {
        real = real + c.real;
        imag = imag + c.imag;
    }
}
public class Main
{
    public static void main(String args[])
    {
        Complex cc1 = new Complex();
        Complex cc2 = new Complex();
        cc1.input(100,200);
        cc2.input(300,700);
        cc1.show();
        cc2.show();
        System.out.println("");
        cc1.add(cc2);
        cc1.show();
        cc2.show();
    }
}

Output

100+200i
300+700i

400+900i
300+700i

Passing Object as argument (format like y= x + y)

//Passing Object as argument (y=x+y)
class Complex
{
    private int real, imag;
    void input(int r, int im)
    {
        real = r;
        imag = im;
    }
    void show()
    {
        System.out.println(real+"+"+imag+"i");
    }
    void add(Complex c)
    {
        c.real = real + c.real;
        c.imag = imag + c.imag;
    }
}
public class Main
{
    public static void main(String args[])
    {
        Complex cc1 = new Complex();
        Complex cc2 = new Complex();
        cc1.input(100,200);
        cc2.input(300,700);
        cc1.show();
        cc2.show();
        System.out.println("");
        cc1.add(cc2);
        cc1.show();
        cc2.show();
    }
}

OutPut

100+200i
300+700i

100+200i
400+900i

Passing Object as argument (format like r= x + y)

//Passing Object as argument (r=x+y) where r denotes result
class Complex
{
    private int real, imag;
    void input(int r, int im)
    {
        real = r;
        imag = im;
    }
    void show()
    {
        System.out.println(real+"+"+imag+"i");
    }
    void add(Complex c1, Complex c2)
    {
        real = c1.real + c2.real;
        imag = c1.imag + c2.imag;
    }
}
public class Main
{
    public static void main(String args[])
    {
        Complex cc3 = new Complex();
        Complex cc1 = new Complex();
        Complex cc2 = new Complex();
        cc1.input(100,200);
        cc2.input(300,700);
        cc1.show();
        cc2.show();
        System.out.println("");
        cc3.add(cc1,cc2);
        cc3.show();
    }
}

Output

100+200i
300+700i

400+900i

Erase Me! Before Start Code

Leave a Comment

Item added to cart.
0 items - 0.00