Monday, June 1, 2020

Classes and Objects in Java

 Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities
. A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
Objects: collection of data (variable) and methods(functions)Class (blueprint for the object)
  • Real world entities that has their own properties and behavior
  • Examples laptop, mobile phone, chair, table, fan etc
  • Blueprint from which an objects properties and behaviors are decided
  • These properties and behaviors will be written in the class to describe the object
  • (blueprint or drawing of object)
null
  • Class- state (variable-what classes has and how it behaves) and behavior
  • Object creation is called instantiation
  • In object-oriented program, programs are viewed as collection of objects
  • Object has three characteristics: state(variable), behavior (method), and identity.
  • State of object: set of data field with their current values
  • Behavior of object: how an object act and react in terms of state change and message passing
Ways to create object:
  1. new keyword
  2. instance factory method
  3. static factory method
  4. pattern factory method
  5. newInstance() method
  6. clone() method
  7. Deserialization

package com.cerotid.oo.principles;
 class Product {
        //Attributes (States)
       private int pid;
        String pname;
        int pprice;
       
        //constructor
        Product(){
              System.out.println("Product object constructor");
        }
        //Methods
        //To write data in Product object
        void setProductDetails(int pid, String pname, int pprice) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
        }
        //To read data from Product object
       void showProductDetails() {
             System.out.println("........Product ID: "+pid+ "...........");
             System.out.println("Name: "+pname);
             System.out.println("Price: "+pprice);
       }
       
 //setter:is a method that updates the value of a variable
 void setPid(int pid) {
        this.pid = pid;// this means reference to current object
        //LHS belongs to the object and RHS belongs to method
 }
 //getter:is a method that reads a value of variable
 int getPid() {
        return pid;
 }
 }
public class InheritanceDemo2 {
//main is executed by JVM when my program run
       public static void main(String[] args) {
             
             //create an object: Product
             Product product1 = new Product();
             //product is not an object, its a reference variable which holds the hashCode of the object in hexadecimal notation
       System.out.println("Product is: "+product1);
       
       //Writing data in object
       product1.setProductDetails(111, "iPhone 6", 720);
       
       //Reading data from object
       product1.showProductDetails();
       
       //Lets write the data directly
       Product product2 = new Product();
       //product2.pid = 222;
       product2.setPid(222);
       product2.pname = "iPhone 7";
       product2.pprice = 800;
       
       //Reading data from object
       product2.showProductDetails();
       }
}

Output:
Product object constructor
Product is: com.cerotid.oo.principles.Product@15db9742
........Product ID: 111...........
Name: iPhone 6
Price: 720
Product object constructor
........Product ID: 222...........
Name: iPhone 7
Price: 800
Format of object creation:
  1. Named object approach: Test t = new Test(); where Test........class name, t..............object name, new.............keyword, Test(); constructor
  2. Nameless approach: new Test();
Three methods to initialize an object:
  1. using constructor: store data into object using constructor
  2. using method: store data into object by invoking a method
  3. using reference variable: store data into object through reference variable

Examples: 

public class Student {
int sid;
String sname;
Student(){
       System.out.println("Student id: "+sid);
       System.out.println("Student name: "+sname);
}
Student(int sid, String sname){
       System.out.println("Student id: "+sid);
       System.out.println("Student name: "+sname);
       this.sid = sid;
       this.sname = sname;
}
void display() {
       System.out.println("Student id: "+sid);
       System.out.println("Student name: "+sname);
}
public static void main(String[] args) {
       Student s1 = new Student();                
       Student s2 = new Student(111, "Ram");             //initialize object by using constructor
       Student s3 = new Student(222, "Babita");
       
       s1.display();                                   // initialize object by calling method
       s2.display();
       s3.display();
       
       s1.sid = 111;                                   //initialize object through reference variable
       s1.sname = "Ram";
       s2.sid = 222;
       s2.sname = "Babita";
       System.out.println("Student id: "+s1.sid);
       System.out.println("Student name: "+s1.sname);
       
       System.out.println("Student sid: "+s2.sid);
       System.out.println("Student sname: "+s2.sname);
}
}
Output:
Student id: 0
Student name: null
Student id: 111
Student name: Ram
Student id: 222
Student name: Babita
Student id: 0
Student name: null
Student id: 111
Student name: Ram
Student id: 222
Student name: Babita
Student id: 111
Student name: Ram
Student sid: 222
Student sname: Babita

The most important Example ever:

class Product{            //using class you are actually describing the object
       //whatever you write in class is actual property of object as we are describing the object
       //Attributes
       int pid;
       String pname;
       int pprice;
       //default constructor-to initialize the object
       Product(){
             System.out.println("Product object constructed");
       }
       
       // Methods(behavior)-to write the data in Product object
       void setProductDetails(int pid, String pname, int pprice) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
       }
             
             //Method-to read from Product object
             void showProductDetails() {
                    System.out.println("Product id is: "+pid);
                    System.out.println("Product name is: "+pname);
                    System.out.println("Product price is: "+pprice);
       }
}
public class InheritanceDemo1 {
       
       //main is executed by JVM when my program run!!
public static void main(String[] args) {
       
       //create an object
       Product p = new Product();
       //p is a reference variable which holds the hashcode of the object in hexadecimal notation
       //System.out.println("Product is: "+p);//input
       //Output-Product is: com.cerotid.inheritance.Product@15db9742
       
       //Writing data in object
       p.setProductDetails(101, "iPhone6", 600);
       
       //Reading data from object
       p.showProductDetails();
       
       System.out.println("...............................");
       //Lets us write the data directly-using reference variable
       Product p1 = new Product();
       p1.pid = 201;
       p1.pname = "iPhone 6+";
       p1.pprice = 800;
       p1.showProductDetails();
}
}
Output:
Product object constructed
Product id is: 101
Product name is: iPhone6
Product price is: 600
...............................
Product object constructed
Product id is: 201
Product name is: iPhone 6+
Product price is: 800


After marking pid as private:
class Product{            //using class you are actually describing the object
    //whatever you write in class is actual property of object as we are describing the object
    //Attributes
    private int pid;
    String pname;
    int pprice;
   
    public int getPid() {
          return pid;
    }
    public void setPid(int pid) {
          this.pid = pid;
    }
    //default constructor-to initialize the object
    Product(){
          System.out.println("Product object constructed");
    }
   
    // Methods(behavior)-to write the data in Product object
    void setProductDetails(int pid, String pname, int pprice) {
          this.pid = pid;
          this.pname = pname;
          this.pprice = pprice;
    }
         
          //Method-to read from Product object
          void showProductDetails() {
                 System.out.println("Product id is: "+pid);
                 System.out.println("Product name is: "+pname);
                 System.out.println("Product price is: "+pprice);
    }
}
public class InheritanceDemo1 {
   
    //main is executed by JVM when my program run!!
public static void main(String[] args) {
   
    //create an object
    Product p = new Product();
    //p is a reference variable which holds the hashcode of the object in hexadecimal notation
    //System.out.println("Product is: "+p);//input
    //Output-Product is: com.cerotid.inheritance.Product@15db9742
   
    //Writing data in object
    p.setProductDetails(101, "iPhone6", 600);
   
    //Reading data from object
    p.showProductDetails();
   
    System.out.println("...............................");
    //Lets us write the data directly-using reference variable
    Product p1 = new Product();
    //p1.pid = 201;                //private variables can not be accessed directly outside of the class
    p1.setPid(301);
    p1.pname = "iPhone 6+";
    p1.pprice = 800;
    p1.showProductDetails();
}
}
Output:
Product price is: 600
...............................
Product object constructed
Product id is: 301
Product name is: iPhone 6+
Product price is: 800
Example showing inheritance:
class Product{            //using class you are actually describing the object
    //whatever you write in class is actual property of object as we are describing the object
    //Attributes
    private int pid;
    String pname;
    int pprice;
   
    public int getPid() {
          return pid;
    }
    public void setPid(int pid) {
          this.pid = pid;
    }
    //default constructor-to initialize the object
    Product(){
          System.out.println("Product object constructed");
    }
   
    // Methods(behavior)-to write the data in Product object
    void setProductDetails(int pid, String pname, int pprice) {
          this.pid = pid;
          this.pname = pname;
          this.pprice = pprice;
    }
         
          //Method-to read from Product object
          void showProductDetails() {
                 System.out.println("Product id is: "+pid);
                 System.out.println("Product name is: "+pname);
                 System.out.println("Product price is: "+pprice);
    }
}
class Mobile extends Product{
    String os;
    int ram;
    int sdCardSize;
    Mobile(){
          System.out.println("Mobile object constructed");
    }
}
public class InheritanceDemo1 {
   
    //main is executed by JVM when my program run!!
public static void main(String[] args) {
   
    Mobile m = new Mobile();
    //Product object gets constructed before the Mobile Object!!
    m.setProductDetails(401, "iPhone 8", 900);
    m.showProductDetails();
}
}
Output:
Product object constructed
Mobile object constructed
Product id is: 401
Product name is: iPhone 8
Product price is: 900

Method Overloading Example:
class Product{            //using class you are actually describing the object
       //whatever you write in class is actual property of object as we are describing the object
       //Attributes
       int pid;
       String pname;
       int pprice;
       
       public int getPid() {
             return pid;
       }
       public void setPid(int pid) {
             this.pid = pid;
       }
       //default constructor-to initialize the object
       Product(){
             System.out.println("Product object constructed");
       }
       
       // Methods(behavior)-to write the data in Product object
       void setProductDetails(int pid, String pname, int pprice) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
       }
             
             //Method-to read from Product object
             void showProductDetails() {
                    System.out.println("Product id is: "+pid);
                    System.out.println("Product name is: "+pname);
                    System.out.println("Product price is: "+pprice);
       }
}
class Mobile extends Product{
       String os;
       int ram;
       int sdCardSize;
       Mobile(){
             System.out.println("Mobile object constructed");
       }
       
       //We have redefined the same method from Parent into Child with differnt input
       //Now Child has two methods, one from Parent and one in child
       //These methods are different based on input even though they have same name
       //Method Overloading: Same method name with different input
       void setProductDetails(int pid, String pname, int pprice, String os, int ram, int sdCardSize) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
             this.os =os;
             this.ram = ram;
             this.sdCardSize = sdCardSize;
       }
}
public class InheritanceDemo1 {
       
       //main is executed by JVM when my program run!!
public static void main(String[] args) {
       
       Mobile m = new Mobile();
       //Product object gets constructed before the Mobile Object!!
       //m.setProductDetails(401, "iPhone 8", 900);
       //m.showProductDetails();
       m.setProductDetails(501, "iPhone 10", 1400, "iOS", 8, 128);
       m.showProductDetails();
}
}
Output:
Product object constructed
Mobile object constructed
Product id is: 501
Product name is: iPhone 10
Product price is: 1400

Method Overridding Example:
class Product{            //using class you are actually describing the object
       //whatever you write in class is actual property of object as we are describing the object
       //Attributes
       int pid;
       String pname;
       int pprice;
       
       public int getPid() {
             return pid;
       }
       public void setPid(int pid) {
             this.pid = pid;
       }
       //default constructor-to initialize the object
       Product(){
             System.out.println("Product object constructed");
       }
       
       // Methods(behavior)-to write the data in Product object
       void setProductDetails(int pid, String pname, int pprice) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
       }
             
             //Method-to read from Product object
             void showProductDetails() {
                    System.out.println("Product id is: "+pid);
                    System.out.println("Product name is: "+pname);
                    System.out.println("Product price is: "+pprice);
       }
}
class Mobile extends Product{
       String os;
       int ram;
       int sdCardSize;
       Mobile(){
             System.out.println("Mobile object constructed");
       }
       
       //We have redefined the same method from Parent into Child with differnt input
       //Now Child has two methods, one from Parent and one in child
       //These methods are different based on input even though they have same name
       //Method Overloading: Same method name with different input
       void setProductDetails(int pid, String pname, int pprice, String os, int ram, int sdCardSize) {
             this.pid = pid;
             this.pname = pname;
             this.pprice = pprice;
             this.os =os;
             this.ram = ram;
             this.sdCardSize = sdCardSize;
       }
       
       //Let us redefine showProductDetails as well
// We have two methods in Child class one from Parent and one in the Child,  with the same name and input
       //Child method will be executed not Parent method
       //Overriding: Same method name with same inputs in Parent Child Relationship
       void showProductDetails() {
             System.out.println("Product id is: "+pid);
             System.out.println("Product name is: "+pname);
             System.out.println("Product price is: "+pprice);
             System.out.println("Product os is: "+os);
             System.out.println("Product ram is: "+ram);
             System.out.println("Product sdCardSize is: "+sdCardSize);
}
}
public class InheritanceDemo1 {
       
       //main is executed by JVM when my program run!!
public static void main(String[] args) {
       
       Mobile m = new Mobile();
       //Product object gets constructed before the Mobile Object!!
       //m.setProductDetails(401, "iPhone 8", 900);
       //m.showProductDetails();
       m.setProductDetails(501, "iPhone 10", 1400, "iOS", 8, 128);
       m.showProductDetails();
}
}
Output:
Product object constructed
Mobile object constructed
Product id is: 501
Product name is: iPhone 10
Product price is: 1400
Product os is: iOS
Product ram is: 8
Product sdCardSize is: 128


Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java
  1. //Java Program to demonstrate having the main method in   
  2. //another class  
  3. //Creating Student class.  
  4. class Student{  
  5.  int id;  
  6.  String name;  
  7. }  
  8. //Creating another class TestStudent1 which contains the main method  
  9. class TestStudent1{  
  10.  public static void main(String args[]){  
  11.   Student s1=new Student();  
  12.   System.out.println(s1.id);  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  
Output:
0
null

3 Ways to initialize object

There are 3 ways to initialize object in Java.
  1. By reference variable
  2. By method
  3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
File: TestStudent2.java
  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent2{  
  6.  public static void main(String args[]){  
  7.   Student s1=new Student();  
  8.   s1.id=101;  
  9.   s1.name="Sonoo";  
  10.   System.out.println(s1.id+" "+s1.name);//printing members with a white space  
  11.  }  
  12. }  
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent3{  
  6.  public static void main(String args[]){  
  7.   //Creating objects  
  8.   Student s1=new Student();  
  9.   Student s2=new Student();  
  10.   //Initializing objects  
  11.   s1.id=101;  
  12.   s1.name="Sonoo";  
  13.   s2.id=102;  
  14.   s2.name="Amit";  
  15.   //Printing data  
  16.   System.out.println(s1.id+" "+s1.name);  
  17.   System.out.println(s2.id+" "+s2.name);  
  18.  }  
  19. }  
Output:
101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  void insertRecord(int r, String n){  
  5.   rollno=r;  
  6.   name=n;  
  7.  }  
  8.  void displayInformation(){System.out.println(rollno+" "+name);}  
  9. }  
  10. class TestStudent4{  
  11.  public static void main(String args[]){  
  12.   Student s1=new Student();  
  13.   Student s2=new Student();  
  14.   s1.insertRecord(111,"Karan");  
  15.   s2.insertRecord(222,"Aryan");  
  16.   s1.displayInformation();  
  17.   s2.displayInformation();  
  18.  }  
  19. }  
Output:
111 Karan
222 Aryan
null
As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
  1. class Employee{  
  2.     int id;  
  3.     String name;  
  4.     float salary;  
  5.     void insert(int i, String n, float s) {  
  6.         id=i;  
  7.         name=n;  
  8.         salary=s;  
  9.     }  
  10.     void display(){System.out.println(id+" "+name+" "+salary);}  
  11. }  
  12. public class TestEmployee {  
  13. public static void main(String[] args) {  
  14.     Employee e1=new Employee();  
  15.     Employee e2=new Employee();  
  16.     Employee e3=new Employee();  
  17.     e1.insert(101,"ajeet",45000);  
  18.     e2.insert(102,"irfan",25000);  
  19.     e3.insert(103,"nakul",55000);  
  20.     e1.display();  
  21.     e2.display();  
  22.     e3.display();  
  23. }  
  24. }  
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.  void insert(int l, int w){  
  5.   length=l;  
  6.   width=w;  
  7.  }  
  8.  void calculateArea(){System.out.println(length*width);}  
  9. }  
  10. class TestRectangle1{  
  11.  public static void main(String args[]){  
  12.   Rectangle r1=new Rectangle();  
  13.   Rectangle r2=new Rectangle();  
  14.   r1.insert(11,5);  
  15.   r2.insert(3,15);  
  16.   r1.calculateArea();  
  17.   r2.calculateArea();  
  18. }  
  19. }  
Output:
55
45

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:
  • By new keyword
  • By newInstance() method
  • By clone() method
  • By deserialization
  • By factory method etc.
We will learn these ways to create object later.

No comments:

Post a Comment