Blog

Classes and Objects in Java

  • (4.0)
  • | 133 Ratings |
  • Last Updated February 08, 2019

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities.

Create a Classes in Java

 A class is at the core of Java. It is a template of an object and an object is an instance of a class. Class determines the object’s behaviour and what it will contain. here I provide basic syntax of Create Classes in Java is as below:

class classname {
 
type instance-var1;
type instance-var2;
//
type instance-varN;
 
type method1(parameter-list) {
// body of method1
}
.
.
type methodN(parameter-list) {
// body of methodN
}
}
}

Variables defined in the class are instance variables as each instance of the class will have their own copies of the variables. And all the variables and methods defined in the class are called members of the class. Classes behave as a data type which we can use to declare any variable of that type.

Below is the sample class defined in Java:

class Person {
  String name;
  int age;
  int height;
  int weight;
  Strin
}

Objects and Methods in java

Object is an instance of the class. Objects have properties and behaviour. Properties are stored in object variables and behaviours are determined by methods like shown in below example.

img

Declaration of an object is divided into 2 parts.

Declare a variable of class type:

Person p;

Acquire physical copy of an object and assign it to the variable using new operator

p = new Person();

These 2 parts can be combined in one line as well like below:

Person p = new Person();

When we declare any object of a class, it acquires a memory location. Now let us understand how method uses these variables and make the code useful.

General form of a method is as below:

type methodname(parameter-list) {
// body of method
}

Here type specifies the type of the value returned by a method. If method is having a void datatype then it means method doesn’t return any value. Let us understand the usage of methods in Java with below example.

public class PersonDemo{
 
     public static void main(String []args){
        Person p = new Person();
        p.name = "XYZ";
        p.height = 6;
        p.weight = 50;
        p.age = 25;
        p.gender = "Male";
        p.printInformation();
       
        Person q = new Person();
        q.name = "ABC";
        q.height = 5;
        q.weight = 45;
        q.age = 19;
        q.gender = "Female";
        q.printInformation();
       
     }
}
 
class Person{
 
  String name;
  int age;
  int height;
  int weight;
  String gender;
 
 
void printInformation() {
    System.out.println("Person Details");
    System.out.println("Name :" + name);
                System.out.println("Gender :"+ gender);
                System.out.println("Age :" +age);
                System.out.println("Height :"+ height);
                System.out.println("Weight :"+ weight);
}
}

Output:

Person Details
Name :XYZ
Gender :Male
Age :25
Height :6
Weight :50
Person Details
Name :ABC
Gender :Female
Age :19
Height :5
Weight :45

To invoke the method for any object, we need to use object name followed by dot operator and method name. Here the method printInformation() prints the details of a specified person. Here when method was called for object p, it printed all the details for that object only. And when it was called by object q, it printed all the details which was assigned to object q. This is why it is called that each object has its own copy of class.

Methods can return values as well on based on the type used while defining method. We can also pass parameters to the method and use those values to process and use further in code. Let us see how we can do this by following example:

public class methodsDemo{
 
     public static void main(String []args){
         squareDemo p = new squareDemo();
        int a,b;
                               
                                a = p.getSquare();
                                System.out.println("Square of "+2+" :" + a);
                               
                                p.getSquare1(10);
                                b = p.getSquare2(5);
                                System.out.println("Square of "+5+" :" + b);
       
     }
}
 
class squareDemo{
 
int getSquare()
{
    return 2*2;
}
 
void getSquare1(int i)
{
                System.out.println("Square of "+i+" :" + (i * i));
}
  
int getSquare2(int i)
{
                return i * i;
}

Output:

Square of 2 :4
Square of 10 :100
Square of 5 :25

Here in this example,

  • getSquare method returns the square of 2
  • getSquare1() method is parameterized method but doesn’t return any value
  • getSquare2() method accepts the parameters and returns the square of the value.

getSquare method returns the square of the value but its usage is very limited as it will return square of 2 for every object. However, if we modify the method and make it like getSquare1 which accepts the parameter, then it becomes more useful as it will print out the square of any passed variable instead of 2. We can have the method getSquare2 which returns the square of any passed value instead of printing it. Now this has become a general-purpose method which we can use for computing square of any integer variable just by passing that value.

Constructors in Java

Initializing all the variables whenever we create an instance of a class is a tedious task. If all initializations will be done while creating an object, it will become simpler and concise. Constructors are the way to provide automatic initialization whenever any object is created. It looks like method and have same name as class name. Constructors don’t have any return type as it returns the class object implicitly. Constructors are called immediately once the object is created, just before the new operator. Let’s rework the class person to initialize the values at the object creation.

public class personDemo{
 
     public static void main(String []args){
        Person p = new Person();
        p.printInformation();
       
        Person q = new Person();
        q.printInformation();
       
     }
}
 
class Person{
 
  String name;
  int age;
  int height;
  int weight;
  String gender;
 
Person() //constructor
{
    System.out.println("Person Constructor");
    name = "XYZ";
    height = 6;
    weight = 50;
    age = 25;
    gender = "Male";
}
 
void printInformation() {
    System.out.println("Person Details");
    System.out.println("Name :" + name);
                System.out.println("Gender :"+ gender);
                System.out.println("Age :" +age);
                System.out.println("Height :"+ height);
                System.out.println("Weight :"+ weight);
}
}

Output:

Person Constructor
Person Details
Name :XYZ
Gender :Male
Age :25
Height :6
Weight :50
Person Constructor
Person Details
Name :XYZ
Gender :Male
Age :25
Height :6
Weight :50

Here we can see both the objects p and q are initialized with values when they got created.
Now if all the objects will have same value then it won’t become useful. So, in that case we can use parameterized constructors. So, you can pass values with which you want the object to be initialized while creating those objects. Let’s rework the above code by using parameterized constructors.

public class personDemo{
 
     public static void main(String []args){
        Person p = new Person("XYZ",7,60,25,"Male");
        p.printInformation();
       
        Person q = new Person("ABC",5,50,30,"Female");
        q.printInformation();
       
     }
}
 
class Person{
 
  String name;
  int age;
  int height;
  int weight;
  String gender;
 
Person(String n, int h, int w, int a, String g)
{
    System.out.println("Person Constructor");
    name = n;
    height = h;
    weight = w;
    age = a;
    gender = g;
}
 
void printInformation() {
    System.out.println("Person Details");
    System.out.println("Name :" + name);
                System.out.println("Gender :"+ gender);
                System.out.println("Age :" +age);
                System.out.println("Height :"+ height);
                System.out.println("Weight :"+ weight);
}
}

Output:

Person Constructor
Person Details
Name :XYZ
Gender :Male
Age :25
Height :7
Weight :60
Person Constructor
Person Details
Name :ABC
Gender :Female
Age :30
Height :5
Weight :50

Here we can see, each object is initialized with the values specified and passed to constructors’ parameters. This is very useful and removes the redundancy of the code.

Garbage Collection in Java

In Java, objects are dynamically created using new operator and assigned a memory space. Java has a mechanism called garbage collection, to de-allocate such objects automatically. When there is no reference to an object exists, it is considered that object is not required anymore and that space can be released and reclaimed. This process happens automatically during program runtime. So, developers do not have to think while coding any programs.

Access Modifiers in Java

As the name implies, access modifiers in Java are used to control the scope of classes, variables, methods or constructors. It is not necessary that all modifiers will be applicable for all; few are for classes whereas few are for methods or variable. Moreover, there will be few which are applicable to both.

Once program has access to a class, it also gives the program accessibility of that class’ members.

There are four types of access modifiers used in Java:

  • Default – No keyword required
  • Private
  • Protected
  • Public

Other modifiers used with class are: static, final and strictfp.

If a class is public, that means it is visible to all other classes. But if it has no modifier that means it is a default class and only visible in its own package. 

In Selenium, we mainly use public, private and protected access modifiers to create our automation scripts. So, let us understand them in detail what they are and how we can use them in our scripts.

Public

The public access modifier is described with the keyword public. It has the greatest scope amongst all other access modifiers. No restriction is set on the scope of public data members. When classes, methods or data members are defined as public then they are reachable from everywhere (Not only inside the package, also from outside the package.) Below is an example for same:

Example:

package pack1; 
 
public class printstring 
{ 
   public void print() 
      { 
          System.out.println("Learn Java for Selenium"); 
      } 
} 
 
package pack2; 
 
import pack1.*; 
class demo 
{ 
    public static void main(String args[]) 
      { 
          printstring obj = new printstring; 
          obj.print(); 
      } 
}

In above example, we have demo class accessing printstring class’ print() method. If printstring class wasn’t declared as public, then program will end up with compile time error.

Whenever we access any class method or variable, compiler will first check class’ accessibility. So if we have any class which is not public but its methods and variable are declared as public, in that case we won’t be able to access those variables or methods as class is not set as public even though variables/methods are declared public. In that case, compiler will give error.

Private

The private access modifier is described with the keyword private.  Private means it is only reachable within the same class. If methods or any data members are declared as private, then they are only accessible in the same class. They are not accessible from the other classes of the same or different package.  Private modifier is mostly used for methods or variables. 

Example:

package pack1; 
  
class printstring  
{ 
   private void print() 
    { 
        System.out.println("Learn Java for Selenium"); 
    } 
} 
  
class demo 
{ 
   public static void main(String args[]) 
      { 
          printstring  obj = new printstring (); 
          //let’s try to access private method of another class 
          obj.print(); 
      } 
}

Output:

error: print() has private access in printstring
        obj.print();

In above example, demo class is trying to access private method print of printstring class. As it cannot be accessible from the class of same or different package, program will give an error.

Protected

The protected access modifier is described with the keyword protected. If methods or variables are declared as protected then they can be reachable from any class residing in the same package and subclasses of that class in different packages.

Example:

package pack1;
public class printstring
{
   protected void print()
    {
        System.out.println("Learn Java for Selenium");
    }

package pack2;
import pack1.*; 

//Class demo is subclass of printstring
class demo extends printstring
{
   public static void main(String args[])
   {  
       demo obj = new demo();  
       obj.print();  
   }  
Output:

Learn Java for Selenium   
}

In this example, there are two packages pack1 and pack2. Class printstring is declared as public in pack1 so that it is accessible in pack2. Method print in class printstring is protected. So, print() method can be accessible from all the classes of pack1 and any subclasses of printstring class. Class demo in pack2 is inheriting class printstring in pack1. Hence protected method print() is accessible from the object of demo class. 

Let us summarize all access modifiers by putting into a table.

Access Modifier Same class Same package subclass Same package non-subclass Different package subclass Different package non-subclass
Private Y N N N N
Default Y Y Y N N
Protected Y Y Y Y N
Public Y Y Y Y Y

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.


DMCA.com Protection Status