Classes and objects are the basic building blocks of Object Oriented Programming.

Class:

A class is a user defined data type. It’s a blueprint that describes the behavior or state of an object or from which objects can be created. A class does not consume any memory. A class in Java can contain:

  • Fields
  • Methods
  • Blocks
  • Constructors
  • Nested class and interface

Syntax:

class  Class_Name {    //class is a keyword   
     field; // variables
     method;    
}  

For e.g. :

public class Rectangle
  {
     private int l, b;
     public void setDimension(int x, int y)
       {
         l = x;
         b = y;
       }
     public void showDimension()
       {
         System.Out.Println("Length ="+l);
         System.Out.Println("Breadth ="+b);
       }
}

Object:

An object is a real world or run time entity. An object is an instance of class. It can be physical and logical. It’s an entity that has state and behavior. It consumes memory. E.g., car, chair, pen etc.

 An object has three characteristics :

  • State: represents data of an object
  • Behavior: represents the functionality of an object
  • Identity: is implemented by a unique ID which is not visible to users. It is  used internally by JVM.

For e.g.,  Car is an object. Its states are color, model, 4 wheels etc. and its behavior is distance travelled by it, braking, accelerating, etc.

Different ways to create an object:

  • By new keyword- Almost 99% of objects are created by new keyword.
  • By clone() method- Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it. It implements Cloneable Interface.
  • By newInstance method- We use Class.forName and new instnce method. Class.forName actually loads the Class in Java but doesn’t create any Object. To Create an Object of the Class you have to use the new Instance Method of the Class.
  • By factory method- It provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created
    • Objects get memory in heap memory area. new keyword is used to create object which is used to allocate memory at run time.

Implementation: Please find the code for new keyword,clone method,newInstance method,factory method to create an object.

new

       public class Rectangle
     {
       private int l, b;
       public void setDimension(int x, int y)
       {
         l = x;
         b = y;
       }
     public void showDimension()
       {
         System.Out.Println("Length ="+l);
         System.Out.Println("Breadth ="+b);
       }

public static void main(String []args)
   {
     Rectangle Box = new Rectangle();  // making object named Box using “new”           
                                                                      Keyword//
     Box.setDimension(10,8);    // calling function by object

clone

class Student implements Cloneable{
String name;
int rollno;
student(String name, int rollno)
    {
       this.name=name;
       this.rollno=rollno;
     }
public Object clone()throws CloneNotSupportedException
   { 
      return super.clone();
   }
Public static void main(String args[])  
   {
      try{
            student s1= new Student(“Sonali”, 102);    //creating an object
            student s2= (Student)s1.clone();  //creating another object and copying   
  //values of first object s1 to second objects value
  // used to save extra processing task

            System.out.println(s1.name+” ”+s1.rollno); 
            System.out.println(s2.name+” ”+s2.rollno);
        
catch(CloneNotSupportedException c) 
       {
       }
  }
}

new instance

public class Test1
 {
     public Test1()
       {
            System.out.println("Inside Test class constructor");
       }
       public void disc()
         {
           System.out.println("Disc() method called");
          }
 }
 public class Logics 
    {
        public static void main(String args[]) 
           { try 
                    {
                       String someClassName = "com.javainterviewpoint.Test"; 
                       Class class1 = Class.forName(someClassName); 
                       Test1 t = (Test1)class1.newInstance(); // creating object t 
                      t.disc();
                       }
                       catch (ClassNotFoundException c)
                               {
                                     c.printStackTrace();
                                  } 
                        catch (InstantiationException c) 
                          {
                               c.printStackTrace();
                          }
                          catch (IllegalAccessException c) 
                               {
                                     c.printStackTrace();  
                                   } 
                 }
 }

factory

public interface Production {  }
public abstract class Creators 
{
    public void anOperation() 
       {
           Production product = factoryMethod();  //creating object using                 
                                                                           Factory method//
        }
protected abstract Product factoryMethod();
}
public class ConcreteProduction implements Production {  }
public class ConcreteCreators extends Creators 
     {
           protected Product factoryMethod() 
              {
                   return new ConcreteProduction();
               }
   }
public class Client 
    {
           public static void main( String args[] ) 
               {
                        Creators creator = new ConcreteCreators();
                        creators.anOperation();
               }
    }

ACCESS MODIFIERS

Access modifier specifies which classes can access a given class and its field and methods. It helps to restrict the scope of class, variable and method.

Java supports 4 types of accessibility rules or access specifiers :

  • Public – accessible from any class of the package.
  • Private – accessed from the same class in which they are declared.
  • Protected – accessed from any class of same package and child class of other package.
  • Default – accessed only from the class of same package.

Access Modifiers can be used for :

  • Class
  • Member variables
  • Member function
  • With class
    • For inner class – all four access specifiers can be used.
    • For outer class – either public or default(just a class without any specifiers) can be used.

For e.g.:

  public class Vehicle  //outer class
  {
    class Car // inner class
       {
 
       }
 }
 public class Vehicle 
  {      private int x;  //member variable
         public void setSpeed()  //member function
           {
              //data
           }
 }

That’s all I have and thanks a lot for reading. Please let me know if any corrections/suggestions. Please do share and comments if you like the post. Thanks in advance… 😉

Thanks Sonali for helping us to grow day by day. She is passionate to solve challenging problems and loves to play around Java.

Categories: Miscellaneous

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert