Classes and Objects are basic concepts of Object-Oriented Programming that revolve around real-life entities.
The following topics will be covered in this Classes and Objects in Java blog:
Let’s focus on What are Classes and Objects in Java one by one in detail.
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 behavior and what it will contain. here I provide the 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 its 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
}
The object is an instance of the class. Objects have properties and behavior. Properties are stored in object variables and behaviors are determined by methods like shown the below example.
The Declaration of an object is divided into 2 parts.
Declare a variable of class type:
Person p;
Acquire a physical copy of an object and assign it to the variable using the 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 an object of a class, it acquires a memory location. Now let us understand how the method uses these variables and make the code useful.
The 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 the method is having a void data type then it means the method doesn’t return any value. Let us understand the usage of methods in Java with the 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 the value but its usage is very limited as it will return a 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 that we can use for computing the square of any integer variable just bypassing that value.
[Related Article: What is Operators 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 a method and has the same name as the 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.
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.
In Java, objects are dynamically created using a 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.
[Related Article: Socket Programming 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 the program has access to a class, it also gives the program accessibility to that class’s members.
There are four types of access modifiers used in Java:
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 in detail what they are and how we can use them in our scripts.
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 the above example, we have a demo class accessing printstring class’ print() method. If printstring class wasn’t declared as public, then the 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.
Frequently Asked Core Java interview questions
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.
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 them 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 |
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 19 to Dec 04 | View Details |
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.