All in One Oop
All in One Oop
By
To teach the student the concepts of object oriented and procedure programming
Outcomes
Introduction
Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#,
Perl, Python, Ruby, and PHP.
1. Imperative
2. Logical
3. Functional
4. Object-Oriented
Logical Paradigm
Exam: Prolog
Functional Paradigm
The Functional Programming paradigm views all subprograms as functions in the mathematical
sense-informally; they take in arguments and return a single solution. The solution returned is
based entirely on the input, and the time at which a function is called has no relevance. The
computational model is therefore one of function application and reduction.
Languages
The functional programming paradigms has its roots in mathematics and it is language
independent. The key principle of this paradigm is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions. The
function hide their implementation. Function can be replaced with their values without
changing the meaning of the program.
Advantages
The following are desirable properties of a functional language:
The high level of abstraction, especially when functions are used, supresses many of the
details of programming and thus removes the possibility of committing many classes of
errors;
Disadvantages
Objects are organized into classes, from which they inherit methods and equivalent variables.
The object-oriented paradigm provides key benefits of reusable code and code extensibility.
Advantages:
Data security
Inheritance
Code reusability
Flexible and abstraction is also present
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Abstraction
Abstraction can be defined as hiding internal implementation and showing only the required
features or set of services that are offered. This is the most essential part of Object-Oriented
programming.
As a user, we only want that I can use that ATM for the services. We are not interested in
knowing the internal implementation that what is the process happening inside the ATM
Machine like getting card details, validation, etc kind of things. We only have been provided an
interface to interact with that and simply ask for the work. And the internal implementation we
don’t need to know. So that is the Abstraction.
Explanation-
The above image shows the GUI screen of the ATM. In this when we want to withdraw then we
simply use that. For the implementation part, we don’t care.
The same concept is applicable in the programming implementation of the Abstraction. Although
different programming has a different syntax of implementation of Abstraction. But the most
popular programming languages like JAVA use a keyword called abstract which applies to the
class and methods to make a class abstract and achieve abstraction. And it can also be achieved
using the interfaces in java.
C++ achieves it by grouping the attributes and using an access specifier allowing what data is to
be visible outside.
Access Specifiers are the keywords that state, from where the (attributes and methods) of a class
can be accessed. For example – private can only be accessible within the class, the public can
be accessed from anywhere, etc.
Similarly, other programming languages follow their own implementation for achieving
abstraction.
Features of Abstraction –
1. Security- With Abstraction, the Outside persons don’t know the internal implementation
so it makes the classes more secure, so the unauthorized user will not have access to the
data.
2. Easy Enhancement- Suppose in the future we want to change the logic of the
implementation in class, So we don’t have to change the entire external logic which is
Encapsulation
Encapsulation can be defined as the binding of data and attributes or methods and data members
in a single unit. In classes, we have Data and attributes that perform operations on that data.
So according to the OOPs principle of Encapsulation, that data can be merged into a single unit.
Encapsulation enhances more security of the data as everything related to a single task must be
grouped and access to the data is given as per need.
Data Hiding – It means hiding the data of the class and restricting access to the outside
world. Example – Using the access specifier keywords like private that restricts the data to only
accessible and modifiable in the same class. Outside users can not access the data.
Example 1- In the market, Capsules are available to cure different medical problems. Consider
capsule for fever. Now in that capsules, there are different compositions are grouped to make a
complete medicine that cures fever. So the grouping of that compositions into a single unit in the
capsule is a form of encapsulation. Here, consider fever as data, and the capsule as the operations
on the data. So everything is grouped here.
Explanation- In the above image, all the dots represent the compositions for curing the fever (as
per the example). And these are grouped into a capsule. Similarly in programming, when there
are multiple operations related to a particular data are present, then grouping that into a simple
unit is Encapsulation.
Example 2- In a car, we have all the required things to make a car complete. Like engines, gear
shift, Wheels, etc, and these are grouped into a single body that makes a car. It is not like the
wheels are not attached to the car, Engines are misplaced and dragged outside, etc. Everything is
Explanation- In the image we can see that the car has an engine, steering to control, gear shift,
paddles to race and stop the car are present, and these are grouped into a complete car.
So we want the same things in programming also, And that’s what OOP Principle makes it
possible. Similarly, if we take an example more specific to programming then we can state an
example of a LinkedList. We create a node that contains data and this node is related to the
LinkedList class. And Operation on that node like – Add, Delete, Search, etc are grouped into a
single class.
Features of Encapsulation –
Inheritance
Inheritance is the method of acquiring features of the existing class into the new class. Suppose
there is a class, considered as the parent class, that has some methods associated with it. And we
declare a new class, considered as the child class, that has its own methods. So, when a child
class is inherited from the parent class then it will have all the methods associated with parent
class are available in the child class along with the child class own methods also. So that is
Inheritance.
There are two keywords involved in the inheritance – Base and Derived Class.
Base Class – It is also termed the parent class. It is the main class that has the basic properties
and methods which is defined.
Derived Class – This is the extension of the base class and it is also called the child class. It has
the properties and methods that are in the base class with its own features in it.
Polymorphism
For Objects – When any object can hold the reference of its parent object then it is a
polymorphism. To understand this concept more clear, let’s consider an example-
Example – We have Television from different companies, Let’s say Samsung TV, LG TV,
Xiaomi TV, etc. Now if we have to call it then mostly we don’t call it with its brand name. We
simply call it a Television, And it can be of a different brand. But in general, we call it television.
So this can be said to be polymorphism.
Object oriented programming paradigm allows decomposition of the system into the number of
entities called objects and then ties properties and function to these objects. An object’s
properties can be accessed only by the functions associated with that object but functions of one
object can access the function of other objects in the same cases using access specifiers.
Object orientation techniques work more efficiently than traditional techniques due to the
following reasons.
The higher level of abstraction: Top-down approach support abstraction at the Functional
level while object oriented approach support abstraction at the object level.
The seamless transition among different software development phases: It uses the same
language for all phases, which reduces the level of complexity and redundancy makes
software development clear and robust.
Good programming practice: The subroutine and attributes of a class are held together
tightly.
Improves reusability: it supports inheritance due to which classes can be built from each
other. So only difference and enhancement between classes need to be designed and
coded. All the previous functionality remains as it is and can be used without change.
Objects: Objects are nothing but real or abstract items that contain data to define the
object and methods that can manipulate that information. Thus the object is a
combination of data and methods.
In this page, we will learn about Java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only.
object in Java
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when
an object or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
File: Student.java
Output:
0
null
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. By reference variable
2. By method
3. By constructor
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
class Student{
int id;
String name;
}
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
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
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);
}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);
}
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output:
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
Output:
55
45
The most important method in Java is the main() method. If you want to read more about the
main() method, go through the link https://www.javatpoint.com/java-main-method.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class, it
is known as method overloading.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Demo.java
In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max() method
is a method of the Math class that returns the greater of two numbers.
In the above method signature, we see that the method signature has access specifier public,
non-access modifier static, return type int, method name max(), parameter list (int a, int b). In
the above example, instead of defining the method, we have just invoked the method. This is the
advantage of a predefined method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body contains
the steps to check the number is even or odd. If the number is even, it prints the number is even,
else prints the number is odd.
Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the called
method.
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output 1:
Output 2:
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value
of a and b, respectively. Therefore, the method adds the value of a and b and store it in the
variable s and returns the sum.
Addition.java
Output:
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
Display.java
Output:
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of its
class. Let's see an example of an instance method.
InstanceMethodExample.java
Output:
o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.
Example
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data type
that depends on the field. It is used to set the value of the private field.
Example
Student.java
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It
means the class itself must be abstract if it has abstract method. To create an abstract method, we
use the keyword abstract.
Syntax
Demo.java
Output:
Abstract method...
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor. Here 0 and null values are provided by default constructor.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
Output:
111 Karan
222 Aryan
There are many differences between constructors and methods. They are given below.
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
o The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
0 null 0.0
0 null 0.0
Output:
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Output:
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
Output:
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
class A{
A(){
System.out.println("hello a");
}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}
Output:
hello a
10
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}
}
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the
example given below that displays the actual use of this keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}
Output:
Output:
The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.
It is used to reuse one object in many methods.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
Output:
Hello java
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
By providing only a setter or getter method, you can make the class read-only or write-only. In
other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only, you can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and
fast to create an encapsulated class in Java.
Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
File: Student.java
Output:
vijay
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Exam: As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
Output:
meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
onsider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Type casting is when you assign a value of one primitive data type to another type.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}}
Try it Yourself »
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the
value:
Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.
In Java, Method Overloading is not possible by changing the return type of the method only.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method are the same, and
there is IS-A relationship between the classes, so there is method overriding.
Output:
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.
Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super()
or this().
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Test it Now
Output:
animal is created
dog is created
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Output:
1 ankit 45000
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
A method which is declared as abstract and does not have implementation is known as an
abstract method.
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>{
In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
Output:
drawing circle
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank interface.
File: TestInterface2.java
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
Output:
ROI: 9.15
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported in case of an interface because there is
no ambiguity. It is because its implementation is provided by the implementation class. For
example:
interface Printable{
void print();
}
interface Showable{
void print();
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
interface Printable{
void print();
}
Output:
Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:
File: TestInterfaceDefault.java
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output:
drawing rectangle
default method
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.
6) An abstract class can extend another Java class and An interface can extend another Java interface
implement multiple Java interfaces. only.
7) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Let's see a simple example where we are using interface and abstract class both.
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of the m
ethods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
Output:
I am a
I am b
I am c
I am d
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
Output:Hello subpackage
Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
try{
//block of statements
}catch(Exception handler class){
}
try{
//block of statements
} finally {
}
try{
//block of statements
}catch(Exception handler class){
}finally{
}
catch block:
Catch block is used for exception handler. It is used after try block.
try{
//block of statements
}catch(Exception handler class){
}
try{
//block of statements
}finally{
}
try{
//block of statements
}catch(){
}finally{
}
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
Returns the name of the class concatenated with the result of getMessage().
Prints the result of toString() along with the stack trace to System.err, the error output
stream.
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
5.1. Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations, and
annotations ) providing access protection and namespace management.
Programmers can define their own packages to bundle a group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes and
interfaces.
package animals;
interface Animal {
Now, let us implement the above interface in the same package animals −
package animals;
System.out.println("Mammal travels");
return 0;
m.eat();
m.travel();
Import statement in Java is helpful to take a class or all classes visible for a program specified
under a package, with the help of a single statement. It is pretty beneficial as the programmer
do not require to write the entire class definition. Hence, it improves the readability of the
program.
Syntax 1:
import package1[.package2].(*);
package1: Top-level package
package2: Subordinate-level package under package1
*: To import all the classes
A fully-qualified class name in Java contains the package that the class originated from. An
example of this is java.util.ArrayList. The fully-qualified class name can be obtained using the
getName() method.
Output
The fully-qualified name of the class is: java.util.ArrayList
Class c = java.util.ArrayList.class;
String className = c.getName();
System.out.println("The fully-qualified name of the class is: " + className);
ExampleImport.java
import java.util.*; //imports all the classes and interfaces of the util package
public class ExampleImport
{
/* Driver Code */
public static void main(String ar[])
{
System.out.println("Demonstrating use of import statement in Java");
/* Method from java.util.Date class. */
System.out.println(new Date());
}
}
Output:
The Java static import was introduced in JDK version 1.5. With the help of static import, the
static variables and methods of imported classes can be accessed. We don't need to specify the
class name or object name to access the methods or variables. Using a static import statement
saves time because the programmer isn't required to use the class name or object name again and
again.
Syntax:
The following program shows the use of the methods of the Math class without using the static
import statement.
ExampleStaticImport.java
Output:
Square root of 9 = 3
Result of 2 * pi = 6.283185307179586
In the above Java code, the Math class is imported using static import. The methods sqrt(),
round() and variable PI of Math class are directly accessed without using the class name.
When we try to import classes and packages other that those that are available with Java
Standard Library.
JVM verifies the current directly for them, if not available it verifies the set of directories
specified in the ‘CLASSPATH’ environment variable.
CLASSPATH is an environment variable (i.e., global variables of the operating system available
to all the processes) needed for the Java compiler and runtime to locate the Java packages/classes
used in a Java program. (Why not call PACKAGEPATH?) This is similar to another
environment variable PATH, which is used by the Command shell to find the executable
programs.
CLASSPATH can be set in one of the following ways:
1. CLASSPATH can be set permanently in the environment: In Windows, choose control
panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables"
(for all the users) or "User Variables" (only the currently login user) ⇒ choose "Edit"
(if CLASSPATH already exists) or "New" ⇒ Enter "CLASSPATH" as the variable name
⇒ Enter the required directories and JAR files (separated by semicolons) as the value (e.g.,
".;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include
the current working directory (denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
NOTE: For Unixes and Mac OS X: Use forward slash '/' as the directory separator and ':'
as the path seperator, e.g., ".:/usr/local/myproject/classes:/usr/local/tomcat/lib/servlet-
api.jar".
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
4. Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath (or -cp) of the javac and java commands, for example,
Package Scope
Package scope, also known as default or package-private scope, is a visibility modifier that
restricts the accessibility of classes, interfaces, and members (variables, methods, constructors)
within a package. When a class or member is declared with package scope, it is accessible only
within the same package and not from other packages.
In Java, if no visibility modifier (such as public, private, or protected) is specified, the default
visibility is package scope. You can achieve package scope by omitting the visibility modifier
when declaring a class or member.
class MyClass {
void packageScopedMethod() {
}
}
In the above example, MyClass is declared without any visibility modifier, which means it has
package scope. It can be accessed by other classes within the same package
(com.example.package1), but not from classes in other packages.
}
}
However, if you try to access MyClass or its package-scoped methods from a different package,
you would get a compilation error.
// File: com.example.package2.YetAnotherClass.java
package com.example.package2;
Package scope provides a way to control the visibility and encapsulation of classes and members
within a package, ensuring that they are only accessible by the intended components of the same
package.