0% found this document useful (0 votes)
19 views

Java

The document discusses various Java concepts including classes, objects, methods, constructors, inheritance, polymorphism, abstraction, and encapsulation. It provides definitions and examples for each concept.

Uploaded by

Alok Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java

The document discusses various Java concepts including classes, objects, methods, constructors, inheritance, polymorphism, abstraction, and encapsulation. It provides definitions and examples for each concept.

Uploaded by

Alok Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

What is Java?

Java is a programming language and a platform. Java is a high level, robust,


object-oriented and secure programming language.

What is a class in Java


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.

A class in Java can contain:

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

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve
the reusability of code.

Constructors 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.

It is a special type of method which is used to initialize the object.


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.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Math class


Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same results.

Inheritance in Java
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.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

When one class inherits multiple classes, it is known as multiple inheritance.

Single Inheritance Example


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.

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.

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.

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation
represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name,
emailId etc. It contains one more object named address, which contains its own
informations such as city, state, country, zipcode etc. as given below.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Method Overriding in Java


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.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
o Method overriding is used for runtime polymorphism
No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the
method that is already
provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in


two classes that have IS-A
(inheritance) relationship.

3) In case of method overloading, parameter must be In case of method


different. overriding, parameter must be
same.

4) Method overloading is the example of compile time Method overriding is the


polymorphism. example of run time
polymorphism.

5) In java, method overloading can't be performed by Return type must be same or


changing return type of the method only. Return type covariant in method
can be same or different in method overloading. But overriding.
you must have to change the parameter.

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways.

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in Java: compile-time polymorphism and


runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class
extends Bike class and overrides its run() method. We are calling the run method by
the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is invoked
at runtime.

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).

static binding
When type of the object is determined at compiled time(by the compiler), it is known
as static binding.If there is any private, final or static method in a class, there is static
binding.

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Abstract class in Java


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).

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known
as an abstract method.
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.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


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.

16.6M

349

HTML Tutorial

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.
Interface in 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.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Abstract class Interface

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.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.

Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C+
+, we need to use the sizeof operator.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.

C++ vs Java
There are many differences and similarities between the C++ programming

language and Java

. A list of top differences between C++ and Java are given below:

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in Windows-
based, web-based, enterprise, and mobile
applications.

Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. It interpreter for printing systems but later
was an extension of the C extended as a support network computing.
programming language It was designed to be easy to use and
accessible to a broader audience.
.

Goto C++ supports the goto Java doesn't support the goto statement.

statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance through class. It can be achieved by
using interfaces in java
.

Operator C++ supports operator Java doesn't support operator overloading.


Overloading overloading

Pointers C++ supports pointers Java supports pointer internally. However,


you can't write the pointer program in java.
. You can write a pointer program
It means java has restricted pointer support
in C++.
in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter.
Interpreter compiled and run using the Java source code is converted into bytecode
compiler which converts source at compilation time. The interpreter executes
code into machine code so, C++ is this bytecode at runtime and produces
platform dependent. output. Java is interpreted that is why it is
platform-independent.

Call by Value and C++ supports both call by value Java supports call by value only. There is no
Call by reference and call by reference. call by reference in java.

Structure and C++ supports structures and Java doesn't support structures and unions.
Union unions.

Thread Support C++ doesn't have built-in support Java has built-in thread
for threads. It relies on third-party
support.
libraries for thread support.

Documentation C++ doesn't support Java supports documentation comment


comment documentation comments. (/** ... */) to create documentation for java
source code.

Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can override
that we can decide whether or not all non-static methods by default. In other
to override a function. words, non-static methods are virtual by
default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.

Inheritance Tree C++ always creates a new Java always uses a single inheritance tree
inheritance tree. because all classes are the child of the
Object class in Java. The Object class is the
root of the inheritance

tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented Java is also an object-oriented


language. However, in the C
language. However, everything (except
language, a single root hierarchy is
fundamental types) is an object in Java. It is
not possible.
a single root hierarchy as everything gets
derived from java.lang.Object.

Note

o Java doesn't support default arguments like C++.


o Java does not support header files like C++. Java uses the import keyword to include
different classes and methods.

Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.

Skip Ad

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent

Java is platform independent because it is different from other languages like C, C+


+, etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.

You might also like