Java Objects and Classes Explained
Java Objects and Classes Explained
Java Class: A class is a blueprint for the object. Before we create an object, we
first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows, etc. Based on these descriptions we build
the house. House is the object. Since many houses can be made from the same
description, we can create many objects from a class.
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object
respectively.
● fields are used to store data
● methods are used to perform some operations
In the above example, we have created a class named Bicycle. It contains a field
named gear and a method named braking(). Here, Bicycle is a prototype. Now, we
can create any number of bicycles using the prototype. And, all the bicycles will
share the fields and methods of the prototype.
class Bike1{
//creating a default constructor
Bike1(){
[Link]("Bike is created");
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
class Student4{
int id;
String name;
id = i;
name = n;
[Link]();
[Link]();
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
class Student5{
int id;
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
[Link]();
[Link]();
There are many ways to copy the values of one object into another in Java. They are:
● By constructor
● By assigning the values of one object into another
● By clone() method of Object class
class Student6{
int id;
String name;
id = i;
name = n;
Student6(Student6 s){
id = [Link];
name =[Link];
[Link]();
[Link]();
We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
id = i;
name = n;
Student7(){}
[Link]=[Link];
[Link]=[Link];
[Link]();
[Link]();
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
a. Integer Datatype in Java: int is used for storing integer values. Its size is 4
bytes and has a default value of 0. The maximum value of integer is 2^31 and the
minimum value is -2^31. It can be used to store integer values unless there is a
need for storing numbers larger or smaller than the limits
Example- int a=56;
b. Float Datatype in Java: float is used for storing decimal values. Its default
value is 0.0f and has a size of 4 bytes. It has an infinite value range. However its
always advised to use float in place of double if there is a memory constraint.
Currency should also never be stored in float data type. However it has a single
precision bit.
Example- float a=98.7f;
c. Character Datatype in Java: char as the name suggests is useful for storing
single value characters. Its default value is ‘\u0000’ with the max value being
‘\uffff’ and has a size of 2 bytes.
Example- char a=’D’;
It must be confusing for you to see this new kind of data ‘/u000’. This is the
unicode format which java uses in place of ASCII.
d. Boolean Datatype in Java: boolean is a special datatype which can have only
two values ‘true’ and ‘false’. It has a default value of ‘false’ and a size of 1 byte. It
comes in use for storing flag values.
Example- boolean flag=true;
e. Byte Datatype in Java: It’s an 8 bit signed two’s complement . The range of
values are -128 to 127. It is space efficient because it is smaller than integer data
type. It can be a replacement for int data type usage but it doesn’t have the size
range as the integer datatype.
Example- byte a = 10;
f. Short Datatype in Java: This data type is also similar to the integer datatype.
However it’s 2 times smaller than the integer datatype. Its minimum range is
-32,768 and maximum range is 32,767. It has a size of
Example- short a= 54;
g. Long Datatype in Java: This data type primarily stores huge sized numeric
data. It is a 64 bit integer and ranges from -2^63 to +(2^63)-1. It has a size of 8
bytes and is useful when you need to store data which is longer than int datatype.
Example- long a= 1273762;
h. Double Datatype in Java: This is similar to the float data type. However it has
one advantage over float data type i.e, it has two bit precision over the float data
type which has one bit precision. However it still shouldnt be used for precision
sensitive data such as currency. It has a range of -2^31 to (2^31)-1.
Example- double DataFlair=99.987d;
2. Non-primitive Data Types in Java : These are the datatypes which have
instances like objects. Hence they are called reference variables. They are
primarily classes, arrays, strings or interfaces.
a. Classes in Java: These are the special user defined data type. It has member
variables and class methods. They are blueprinted by objects.
class DataFlair {
int a,
b,
c;
void teach() {
[Link](“Hi I am teaching at DataFlair”);
}
void learn() {
[Link](“Hi I am learning at DataFlair”);.
}
}
c. Arrays in Java : Arrays are special memory locations that can store a collection
of homogeneous data. They are indexed. Arrays always start indexing from 0.
Dynamic allocation of arrays is there in Java. Arrays in Java can be passed as
method parameters, local variables and static fields.
Example- int arr[] = new int[100];
This creates a storage space for 100 integers.
[Link]
int x = 7;
//automatically converts the integer type into long type
long y = x;
float z = y;
Output
Iteration in Java: Java provides a set of looping statements that executes a block
of code repeatedly while some condition evaluates to true. Looping control
statements in Java are used to traverse a collection of elements, like arrays.
while Loop: The while loop statement is the simplest kind of loop statement. It is
used to iterate over a single statement or a block of statements until the specified
boolean condition is false. The while loop statement is also called the entry-control
looping statement because the condition is checked prior to the execution of the
statement and as soon as the boolean condition becomes false, the loop
automatically stops. You can use a while loop statement if the number of iterations
is not fixed. Normally the while loop statement contains an update section where
the variables, which are involved in while loop condition, are updated.
public class WhileLoopDemo {
public static void main(String args[]) {
int num = 10;
while (num > 0) {
[Link](num);
// Update Section
num--;
}
}
}
do-while Loop: The Java do-while loop statement works the same as the while
loop statement with the only difference being that its boolean condition is
evaluated post first execution of the body of the loop. Thus it is also called exit
controlled looping statement. You can use a do-while loop if the number of
iterations is not fixed and the body of the loop has to be executed at least once.
public class Main {
public static void main(String args[]) {
int num = 10;
do {
[Link](num);
num--;
} while (num > 0);
}
}
for Loop: Unlike the while loop control statements in Java, a for loop statement
consists of the initialization of a variable, a condition, and an increment/decrement
value, all in one line. It executes the body of the loop until the condition is false.
The for loop statement is shorter and provides an easy way to debug structure in
Java. You can use the for loop statement if the number of iterations is known.
In a for loop statement, execution begins with the initialization of the looping
variable, then it executes the condition, and then it increments or decrements the
looping variable. If the condition results in true then the loop body is executed
otherwise the for loop statement is terminated.
public class ForLoopDemo {
public static void main(String args[]) {
for (int num = 10; num > 0; num--) {
[Link]( "The value of the number is: " + num );
}
}}
for-each Loop: The for-each loop statement provides an approach to traverse
through elements of an array or a collection in Java. It executes the body of the
loop for each element of the given array or collection. It is also known as
the Enhanced for loop statement because it is easier to use than the for loop
statement as you don’t have to handle the increment operation. The major
difference between the for and for-each loop is that for loop is a general-purpose
loop that we can use for any use case, the for-each loop can only be used with
collections or arrays.
In for-each loop statement, you cannot skip any element of the given array or
collection. Also, you cannot traverse the elements in reverse order using the
for-each loop control statement in Java.
public class ForEachLoopDemo {
public static void main(String args[]) {
int[] array = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
[Link]("Elements of the array are: ");
for (int elem : array) [Link](elem);
}
}
Decision-Making Statements: Decision-making statements in Java are similar to
making a decision in real life, where we have a situation and based on certain
conditions we decide what to do next.
For example, if it's raining outside then we need to carry an umbrella. In
programming also, we have some situations when we need a specific code to be
executed only when a condition is satisfied.
The decision control statements help us in this task by evaluating a boolean
expression and accordingly controlling the flow of the program.
There are four types of decision-making statements in Java:
1. if Statement: These are the simplest and yet most widely used control
statements in Java. The if statement is used to decide whether a particular block of
code will be executed or not based on a certain condition. If the condition is true,
then the code is executed otherwise not.
String role = "admin";
if(role == "admin") {
[Link]("Admin screen is loaded");}
2. if-else Statement: The if statement is used to execute a block of code based on a
condition. But if the condition is false and we want to do some other task when the
condition is false, how should we do it? That's where else statement is used. In this,
if the condition is true then the code inside the if block is executed otherwise
the else block is executed.
String role = "user";
if(role == "admin") {
[Link]("Admin screen is loaded");
}
else {
[Link]("User screen is loaded");}
3. Nested if-else Statement: Java allows us to nest control statements within
control statements. Nested control statements mean an if-else statement inside
other if or else blocks. It is similar to an if-else statement but they are defined
inside another if-else statement. Let us see the syntax of a specific type of nested
control statements where an if-else statement is nested inside another if block.
int age = 20;
String gender = "male";
if (age > 18) {
// person is an adult
if (gender == "male") {
// person is a male
[Link](
"You can shop in the men's section on the 3rd Floor"
);
} else {
// person is a female
[Link]("You can shop in the women's section on 2nd Floor");
}
} else {
// person is not an adult
[Link]("You can shop in the kid's section on 1st Floor");
}
4. switch Statement: Switch statements are almost similar to the if-else-if ladder
control statements in Java. It is a multi-branch statement. It is a bit easier than the
if-else-if ladder and also more user-friendly and readable. The switch statements
have an expression and based on the output of the expression, one or more blocks
of codes are executed. These blocks are called cases. We may also provide a
default block of code that can be executed when none of the cases are matched
similar to the else block.
String browser = "chrome";
switch (browser)
{
case "safari":
[Link]("The browser is Safari");
break;
case "edge":
[Link]("The browser is Edge");
break;
case "chrome":
[Link]("The browser is Chrome");
break;
default:
[Link]("The browser is not supported");
}
Java Identifiers: Identifiers are used to name classes, methods and variables. It
can be a sequence of uppercase and lowercase characters. It can also contain '_'
(underscore) and '$' (dollar) sign. It should not start with a digit(0-9) and not
contain any special characters.
Declaring Variables: Variables are also known as identifiers in Java. It is a named
memory location which contain a value. We are allowed to declare more than one
variable of the same type in a statement.
int var=100;
int g;
char c,d; // declaring more than one variable in a statement
Explanation:
● In the first line, we are declaring a variable of type int and name var and
initialising it with a value.
● The second line is just the declaration of an integer.
● The third line is declaring two characters in one statement.
Rules for Naming a Variable-
● A variable may contain characters, digits and underscores.
● The underscore can be used in between the characters.
● Variable names should be meaningful which depicts the program logic.
● Variable name should not start with a digit or a special character.
● A variable name should not be a keyword.
Java Keywords: Keywords are also known as reserved words in Java. They carry
some predefined meaning and are used throughout the program. They cannot be
used as a variable name. Example: abstract, package, class
Program File Name: So, you must be wondering about the process of naming
your file in Java. In Java, we have to save the program file name with the same
name as that of the name of public class in that file.
The above is a good practice as it tells JVM that which class to load and where to
look for the entry point (main method).
The extension should be java. Java programs are run using the following two
commands:
javac [Link] // To compile the Java program into byte-code
java fileName // To run the program
Array Literal: In a situation where the size of the array and variables of the array
are already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
● The length of this array determines the length of the created array.
● There is no need to write the new int[] part in the latest versions of Java.
Accessing Java Array Elements using for Loop: Each element in the array is
accessed via its index. The index begins with 0 and ends at (total array size)-1. All
the elements of array can be accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i +
" : "+ arr[i]);
Implementation: Java
import [Link].*;
class GFG {
public static void main (String[] args) {
// Syntax
int [][] arr= new int[3][3];
// 3 row and 3 column
}
}
Inheritance:
Inheritance in Java is one of the key features of Object-Oriented Programming. It is
a concept by which objects of one class can acquire the behavior and properties of
an existing parent class. In simple terms, we can create a new class from an
existing class. The newly created class is called subclass (child class or derived
class) that can have the same methods and attributes as the existing
class (superclass or parent class or base class).
Extends keyword: We use the " extends" keyword to demonstrate Inheritance in
Java by creating a derived class from the parent class. The extended keyword is
used to indicate that a specific class is being inherited by another [Link]
example: class A extends B which means class A is being derived from the parent
class B.
Some important terms used to define inheritance in Java
● Class: A class is a blueprint or a template for creating objects.
● Subclass: It is also known as the child class or the derived class that inherits
the properties of the parent class.
● Parent class: It is also known as the superclass or the base class from which
other subclasses inherit the properties.
● Reusability: It is a concept by which we can reuse the methods and the
fields of an existing class in our newly derived class without actually writing
the code again and again.
Example (inheritance in Java): In this Java example code, we have two
classes: A (parent class) and B (derived class, inherited from class A). To
demonstrate the concept of Inheritance in Java, we have firstly created an
object obj of derived class B. We can now access the fields and methods of the
parent class with the help of the object of the derived class.
Code:
class A {
String name;
class B extends A {
class Main {
[Link]();
[Link]("learning");
● A subclass can have only one superclass but a superclass can have any
number of subclasses.
● A subclass can inherit all the members (methods and fields) of the parent
class except the private members.
● The constructors are not considered members of a class and are not inherited
by subclasses.
● While constructors are not inherited by subclasses, subclasses can call their
parent class's constructors using the super keyword, and a default constructor
is automatically created by the Java compiler only if no explicit constructors
are defined in the class.
Method Overriding In Java Inheritance: Have you ever wondered what will
happen if a specific method is present both in the subclass and the superclass? In
such cases, methods of the subclass override the methods of the parent class and
hence, this is known as method overriding in Java. For method overriding, methods
must have the same name & the same number of parameters in the parent and the
child class. This concept is important to achieve run-time polymorphism.
// Parent class
class One {
@Override
class Main {
[Link]("Inheritance");
Types Of Inheritance In Java: There are five types of Java Inheritances and now,
we will study them with their implementation code in Java :
● Single Inheritance
● Multilevel Inheritance
● Hierarchical Inheritance
● Multiple Inheritance
● Hybrid Inheritance
// Parent class
class One {
[Link]("Single ");
// Subclass
[Link]("Inheritance");
class Main {
obj.print_inheritance();
Code:
// Parent class
class One {
[Link]("Multi");
[Link]("level");
}
// Derived class from class Two and
[Link]("Inheritance");
class Main {
obj.print_multi();
obj.print_level();
obj.print_inheritance();
For example:
// Parent Class
class A {
[Link]("Class A");
class B extends A {
[Link]("Class B");
class C extends A {
[Link]("Class C");
class Main {
public static void main(String[] args) {
obj.print_A();
obj.print_B();
obj2.print_A();
obj2.print_C();
For example:
// Implementing Multiple Inheritance using interfaces
interface One {
// Only function definition here
public void print_Hierarchical();
}
interface Two {
public void print_Inheritance();
}
[Link]("Inheritance ");
[Link]("Implementation");
class Main {
obj.print_Hierarchical();
obj.print_Inheritance();
obj.print_Implementation();
}
}
For example:
class C {
[Link]("C");
class A extends C {
[Link]("A");
class B extends C {
[Link]("B");
}
class D extends A {
[Link]("D");
class Main {
[Link]();
}
Encapsulation: Data Encapsulation can be defined as wrapping the code or
methods(properties) and the related fields or variables together as a single unit. In
object-oriented programming, we call this single unit - a class, interface, etc. We
can visualize it like a medical capsule (as the name suggests, too), wherein the
enclosed medicine can be compared to fields and methods of a class.
The variables or fields can be accessed by methods of their class and can be hidden
from the other classes using private access modifiers. One thing to note here is that
data hiding and encapsulation may sound the same but different.
Example of Data Encapsulation: Below is a program to calculate the perimeter of
a rectangle
class Perimeter {
int length;
int breadth;
[Link] = length;
[Link] = breadth;
class Main {
[Link]();
}
}
Data Hiding
Access modifiers are used to achieve data hiding. Access modifiers are the
keywords that specify the accessibility or the scope of methods, classes, fields, and
other members.
Difference between encapsulation and data hiding is that Encapsulation is a way of
bundling data whereas Data Hiding prevents external unauthorized access to the
sensitive data.
The four types of access modifiers in Java are:
● Public: A public modifier is accessible to everyone. It can be accessed from
within the class, outside the class, within the package, and outside the
package.
class A {
// public variables
public int a;
public int b;
// public methods
// Method logic
}}
● Private: A private modifier can not be accessed outside the class. It provides
restricted access. Example:
class A {
// private variables
private String a;
private int b;
}
● Protected: A protected modifier can be accessed from the classes of the
same package and outside the package only through inheritance.
class A {
// protected variables
protected String a;
protected int b;
}
A Private Access Modifier is used for the purpose of Data Hiding. Example of
Data Hiding:
class Employee {
// private variables
[Link] = "James";
[Link]([Link]);
}
}
Getter and Setter Methods: As we can't directly read and set the values of private
variables/fields, Java provides us with getter and setter methods to do so.
How to implement Encapsulation in Java?
We need to perform two steps to achieve the purpose of Encapsulation in Java.
● Use the private access modifier to declare all variables/fields of class as
private.
● Define public getter and setter methods to read and modify/set the values of
the abovesaid fields.
class Book {
//private fields
return author;
[Link] = a;
[Link] = t;
return id;
[Link] = i;
[Link]("Jane Austen");
[Link](775);
[Link]("Book Title: " +[Link]() +"\n" + "Book
Author: " +[Link]() + "\n" +"Book Id: " +[Link]() );
}
Benefits of Encapsulation java
● Cleaner, more organized and less complex code.
● More flexible code as can modify a unit independently without changing any
other unit.
● Makes the code more secure.
● The code can be maintained at any point without breaking the classes that
use the code.
Here, an overridden child class method is called through its parent's reference.
Then the method is evoked according to the type of object. In runtime, JVM
figures out the object type and the method belonging to that object.
Runtime polymorphism in Java occurs when we have two or more classes, and all
are interrelated through inheritance. To achieve runtime polymorphism, we must
build an "IS-A" relationship between classes and override a method.
Method overriding
If a child class has a method as its parent class, it is called method overriding. If
the derived class has a specific implementation of the method that has been
declared in its parent class is known as method overriding.
class Parent {
void print() {
[Link]("Hi I am parent");
}
// Child class extends Parent class
void print() {
[Link]("Hi I am children");
class Overload {
}
// overloading statement method
Parent obj1;
[Link]();
[Link]();
[Link]("Soham.");
[Link]("Soham", "Medewar.");
}
}
Abstraction: Abstraction in Java is a process of hiding the implementation details
from the user and showing only the functionality to the user. It can be achieved by
using abstract classes, methods, and interfaces. An abstract class is a class that
cannot be instantiated on its own and is meant to be inherited by concrete classes.
An abstract method is a method declared without an implementation. Interfaces, on
the other hand, are collections of abstract methods.
Abstraction is a key concept in OOP and in general as well. Think about real world
objects, they are made by combining raw materials like electrons, protons, and
atoms, which we don't see due to the abstraction that nature exposes to make the
objects more understandable. Similarly, in computer science, abstraction is used to
hide the complexities of hardware and machine code from the programmer.
This is achieved by using higher-level programming languages like Java, which are
easier to use than low-level languages like assembly.
Abstraction in Java can be achieved using the following tools it provides :
● Abstract classes
● Interface
Interface:
An interface is a fully abstract class. It includes a group of abstract methods
(methods without a body).
We use the interface keyword to create an interface in Java. For example,
interface Language {
public void getType();
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link](5, 6);
}
}
Output
The area of the rectangle is 30
In the above example, we have created an interface named Polygon. The interface
contains an abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation
of the getArea() method.
Similar to classes, interfaces can extend other interfaces. The extends keyword is
used for extending interfaces. For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class
implements Polygon, it should provide implementations for all the abstract
methods of both Line and Polygon.
Abstract class:
Generally, an abstract class in Java is a template that stores the data members and
methods that we use in a program. Abstraction in Java keeps the user from viewing
complex code implementations and provides the user with necessary information.
We cannot instantiate the abstract class in Java directly. Instead, we can subclass
the abstract class. When we use an abstract class as a subclass, the abstract class
method implementation becomes available to all of its parent classes.
The important rules that we need to follow while using an abstract class in Java are
as follows:
● The keyword "abstract" is mandatory while declaring an abstract class in
Java.
● Abstract classes cannot be instantiated directly.
● An abstract class must have at least one abstract method.
● An abstract class includes final methods.
● An abstract class may also include non-abstract methods.
● An abstract class can consist of constructors and static methods.
Program:
// Abstract class
abstract class Sunstar {
abstract void printInfo();
}
[Link](name);
[Link](age);
[Link](salary);
// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
[Link]();
}
}
Now that the differences between an interface and abstract class are clear, let us
move forward. The next part will explore the crucial advantages and disadvantages
that we must consider while using an abstract class in Java
Packages:
A Java package is a collection of similar types of sub-packages, interfaces, and
classes. In Java, there are two types of packages: built-in packages and
user-defined packages. The package keyword is used in Java to create Java
packages.
Let’s find out why we even need packages in the first place. Say you have a laptop
and a bunch of data you want to store. Data includes your favorite movies, songs,
and images.
So, do you store them all in a single folder or make a separate category for each
one and store them in their corresponding folder?
It is obvious that anyone would like to create separate folders for images, videos,
songs, movies, etc. And the reason is the ease of accessibility and manageability.
User-defined packages
User-defined packages are those that developers create to incorporate different
needs of applications. In simple terms, User-defined packages are those that the
users define. Inside a package, you can have Java files like classes, interfaces, and
a package as well (called a sub-package).
Sub-package:A package defined inside a package is called a sub-package. It’s used
to make the structure of the package more generic. It lets users arrange their Java
files into their corresponding packages. For example, say, you have a package
named cars. You’ve defined supporting Java files inside it.
Example
package [Link];
public interface EventListener
{}
Adds a data type to a class − This situation is where the term, tagging comes
from. A class that implements a tagging interface does not need to define any
methods (since the interface does not have any), but the class becomes an
interface type through polymorphism.