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

OOPs Using Java Notes UNIT-1 (1)

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security features. It supports various applications including desktop, web, enterprise, and mobile applications, and has four main platforms: Java SE, Java EE, Java ME, and JavaFX. Java's design principles emphasize simplicity, robustness, and dynamic capabilities, making it a popular choice for developers.

Uploaded by

TARUNKUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

OOPs Using Java Notes UNIT-1 (1)

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security features. It supports various applications including desktop, web, enterprise, and mobile applications, and has four main platforms: Java SE, Java EE, Java ME, and JavaFX. Java's design principles emphasize simplicity, robustness, and dynamic capabilities, making it a popular choice for developers.

Uploaded by

TARUNKUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT-1

 What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his team changed
the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as


a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

 Java Example

class Abc
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

 Application Of Java

According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

 Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application

Standalone applications are also known as desktop applications or window-based


applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an


enterprise application. It has advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application.


Currently, Android and Java ME are used for creating mobile applications.

 Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang,


java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise


applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP,
Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.


4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API.

 History of Java

The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at
the time. The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital devices
such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is
known as the father of Java, in 1995. James Gosling and his team members started the
project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions, etc. Following are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2) 2) Initially it was designed for small, embedded systems in electronic appliances
like set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was
.gt.
4) After that, it was called Oak and was developed as a part of the Green project.

 Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

 Why Java Programming named "Java"?

7) Why had they chose the name Java for Java language? The team gathered to choose
a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA",
etc. They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having a
cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java.

 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:

 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
 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.

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:

 No explicit pointer
 Java Programs run inside a virtual machine sandbox
 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.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
 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:

 It uses strong memory management.


 There is a lack of pointers that avoids security problems.
 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.
 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++.

Java supports dynamic compilation and automatic memory management (garbage


collection).

 Compilation Flow

When we compile Java program using javac tool, the Java compiler converts the source
code into byte code.
 What happens at runtime?

At runtime, the following steps are performed:

Classloader: It is the subsystem of JVM that is used to load class files.

Bytecode Verifier: Checks the code fragments for illegal code that
can violate access rights to objects.

Interpreter: Read bytecode stream then execute the instructions.

Ques.1 Can you save a Java source file by another name than the
class name?

Yes, if the class is not public. It is explained in the figure given below:

 Fundam
entals of
Object
Oriented
Programming – Procedure Oriented Programming Vs. Object Oriented
Programming (OOP)

Both Procedural Programming and Object Oriented Programming are high-level


languages in programming world and are widely used in the development of
applications. On the basis of nature of developing the code, both languages have
different approaches on basis of which both are differentiate from each other.

1. What is Procedural Programming?

Procedural Programming is a programming language that follows a step-by-step


approach to break down a task into a collection of variables and routines (or
subroutines) through a sequence of instructions. In procedural oriented programming,
each step is executed in a systematic manner so that the computer can understand what
to do.

The programming model of the procedural oriented programming is derived from


structural programming. The concept followed in the procedural oriented programming
is called the "procedure". These procedures consist several computational steps that are
carried out during the execution of a program. Examples of procedural oriented
programming language include – C, Pascal, ALGOL, COBOL, BASIC, etc.

2. What is Object Oriented Programming?

Object-oriented Programming is a
programming language that uses classes
and objects to create models based on
the real world environment. These objects
contain data in the form of attributes and
program codes in the form of methods or
functions. In OOP, the computer programs
are designed by using the concept of
objects that can interact with the real
world entities.

We have several types of object oriented


programming languages, but the most
popular is one among all is class-based
language. In the class-based OOP
languages, the objects are the instances of the classes that determine their types.
Examples of some object oriented programming languages are –
Java, C++, C#, Python, PHP, Swift, etc.

3. The comparison between Procedural programming and object-oriented


programming. We are comparing both terms on the basis of some
characteristics. The difference between both languages are tabulated as
follows :-

S.No. On the basis of Procedural Programming Object-Oriented Programming

1. Definition It is a programming language that is Object-oriented programming


derived from structure programming and is a
based upon the concept of calling computer programming
procedures. It follows a step- by-step design philosophy or
approach in order to break down a task into methodology that
a set of variables and routines via a organizes/ models software
sequence of design around data or
instructions. objects rather than
functions and logic.
2. Security It is less secure than OOPs. Data hiding is possible in
object-oriented programming
due to
abstraction. So, it is more
secure than procedural
programming.

3. Approach It follows a top-down approach. It follows a bottom-up


approach.
4. Data In procedural programming, data moves In OOP, objects can move and
movement freely within the system from one function communicate with
to another. each other via member
functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.


6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.

7. Inheritance Procedural programming does not have the There is a feature of


concept of inheritance. inheritance in object-
oriented programming.
8. Code reusability There is no code reusability present in It offers code reusability by
procedural programming. using the feature of inheritance.

9. Overloading Overloading is not possible in In OOP, there is a concept of


procedural programming. function overloading
and operator overloading.

10. Importance It gives importance to functions over data. It gives importance to data over
functions.

11. Virtual class In procedural programming, there are no In OOP, there is an


virtual classes. appearance of virtual
classes in inheritance.

12. Complex It is not appropriate for complex problems. It is appropriate for


problems complex problems.
13. Data hiding There is not any proper way for data hiding. There is a possibility of data
hiding.
14. Program In Procedural programming, a In OOP, a program is
division program is divided into small divided into small parts
programs that are referred to as that are referred to as
functions. objects.

15. Examples Examples of Procedural The examples of object-


programming include C, Fortran, oriented programming are
Pascal, and VB. -
.NET, C#, Python, Java,
VB.NET, and C++.

 Object oriented programming concepts – Classes, Object, Object Reference,


Abstraction, Encapsulation, Inheritance, Polymorphism, Introduction of
Eclipse (IDE) for developing programs in Java.

1. Java Classes

A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named
Ravi is an object.

Properties of Java Classes :

Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.

Class does not occupy memory.

Class is a group of variables of different data types and a group of methods.

A Class in Java can contain:

 Data member
 Method
 Constructor
 Nested Class
 Interface

class Student {

int id;

String name;

public static void main(String args[]){

Student s1 = new Student();


System.out.println(s1.id);

System.out.println(s1.name);

RESULT:

NULL

class Student {

int id=5;

String name=”Ravi”;

public static void main(String args[]){

Student s1 = new Student();

System.out.println(s1.id);

System.out.println(s1.name);

RESULT:

Ravi

2. Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-
life entities. Objects are the instances of a class that are created to use the attributes
and methods of a class. A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.

 Declaring Objects (Instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of those
attributes, i.e. the state are unique for each object. A single class may have any number
of instances.

 Difference between Java Class and Objects

Class Object
Class is the blueprint of an object. It is An object is an instance of the class.
used to create objects.
No memory is allocated when a class is Memory is allocated as soon as an object
declared. is created.
A class is a group of similar objects. An object is a real-world entity such as a
book, car, etc.
Class is a logical entity. An object is a physical entity.
A class can only be declared once. Objects can be created many times as per
requirement.
An example of class can be a car. Objects of the class car can be BMW,
Mercedes, Ferrari, etc.

 Java Class Attributes


1. Java Class Attributes
We used the term "variable" for x in java program examples. It is actually an attribute of
the class. Or we could say that class attributes are variables within a class:

Example

Create a class called "Main" with two attributes: x and y:

public class Main

int x=5;
int y=3;

“Another term for class attributes is fields.”

2. Accessing Attributes

We can access attributes by creating an object of the class, and by using the dot syntax
(.):

The following example will create an object of the Main class, with the name myObj. We
use the x attribute on the object to print its value:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

3. Modify Attributes

 We can also modify attribute values:

Set the value of x to 40:

public class Main {

int x;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

}
}

 Or override existing values:

public class Main {

int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // x is now 25

System.out.println(myObj.x);

 If you don't want the ability to override existing values, declare the
attribute as “final”:

public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error

System.out.println(myObj.x);

The final keyword is useful when you want a variable to always store the same value.

The final keyword is called a "modifier".

4. Multiple Objects

If we create multiple objects of one class, we can change the attribute values in one
object, without affecting the attribute values in the other:
public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main();

Main myObj2 = new Main();

myObj2.x = 25;

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Result:

5
25

5. Multiple Attributes
We can specify as many attributes as we want:

public class Main {

String fname = "John";

String lname = "Doe";

int age = 24;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Age: " + myObj.age);

}
Result:

Name: John Doe


Age: 24

4. Object Reference

When we create an object with new, the computer creates the object in the
program and then gives us some information about where the object is located.
That location information is what gets stored in the object variable. This is
illustated in the picture below, which shows the object itself as an entity that
exists separate from the variable “a”. The variable a stores information about
where the object is located, which is shown in the picture as an arrow running
from the variable a to the object itself.
Object variables in Java are sometimes referred to as object reference variables,
because their purpose is to refer or point you to the actual object.

 Benefits and Usage of Reference Variables

Reference variables offer several benefits and play a crucial role in Java programming:

o Object Manipulation: Reference variables allow programmers to work with


objects, access their properties, and invoke their methods. They enable object-
oriented programming principles such as encapsulation, inheritance, and
polymorphism.
o Memory Efficiency: Reference variables only store the memory address of an
object rather than the entire object itself. This approach helps conserve memory
by avoiding unnecessary object duplication.
o Object Passing: Reference variables are often used when passing objects as
arguments to methods or returning objects from methods. This allows for
efficient memory usage and facilitates modular programming.
o Dynamic Behavior: Reference variables enable dynamic behavior in Java
programs. Different objects can be assigned to the same reference variable,
allowing flexibility in handling different types of objects at runtime.
o Object Lifetime Control: Using reference variables, developers can control the
lifetime of objects dynamically. When a reference variable is no longer
referencing an object, the object becomes eligible for garbage collection, freeing
up memory resources.

It's important to note that reference variables are distinct from primitive variables in
Java. Primitive variables directly hold the actual values (e.g., int, boolean, etc.) rather
than references to objects.

In conclusion, reference variables in Java provide a mechanism to work with objects by


holding their memory addresses. They enable object manipulation, memory efficiency,
dynamic behavior, and control over object lifetimes. Understanding and effectively using
reference variables is crucial for developing robust and flexible Java applications.

Example:
import java.io.*;

class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}

class Main {
public static void main(String[] args)
{
Demo D1 = new Demo();

System.out.println(D1);

System.out.println(D1.display());
}
}
Output:

Demo@214c265e
x = 10
0

import java.io.*;

class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}

class Main {
public static void main(String[] args)
{
Demo D1 = new Demo();

Demo G1 = D1;

Demo M1 = new Demo();

Demo Q1 = M1;

G1.x = 25;

System.out.println(G1.x);

System.out.println(D1.x);
}
}

Output:

25
25

import java.io.*;
class Demo {
int x = 10;
int y = 20;

int display(Demo A, Demo B)


{
A.x = 95;

System.out.println("x = " + x);

System.out.println("y = " + y);

return 0;
}
}

class Main {
public static void main(String[] args)
{
Demo C = new Demo();

Demo D = new Demo();

D.y = 55;

C.display(C, D);

D.display(C, D);
}
}
Output:

x = 95
y = 20
x = 10
y = 55
import java.io.*;

class Demo {

int Swap(Demo A, Demo B)


{
Demo temp = A;
A = B;
B = temp;
return 0;
}
}
class Main {
public static void main(String[] args)
{
Demo C = new Demo();

Demo D = new Demo();

C.Swap(C, D);
}
}
Output:

??
??
1. Java Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the
user.
Abstraction can be achieved with either abstract classes or interfaces.

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods.

 Ways to achieve Abstraction

There are two ways to achieve abstraction in java++-++


1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class Animal


{
Public abstract void animalSound();
Public void sleep()
{
System.out.println(“Zzz…”);
}
}
Note: From the example above, it is not possible to create an object of the Animal class.
Animal myobj=new Animal();  it will show an error.

Note: To access the abstract class, it must be inherited from another class.
Example:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:

The pig says: wee wee

Zzz

 Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.

 Java Interface

Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related methods with empty bodies:

interface Animal{

public void animalSound();

public void run();


}

Note:To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface method is
provided by the "implement" class.

interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

class Pig implements Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}

Note:

 Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not
possible to create an "Animal" object in the MyMainClass).
 Interface methods do not have a body - the body is provided by the "implement" class.
 On implementation of an interface, you must override all of its methods.
 Interface methods are by default abstract and public.
 Interface attributes are by default public, static and final.
 An interface cannot contain a constructor (as it cannot be used to create objects).

2. Java Encapsulation
Encapsulation is a concept in Java that binds together the data and the methods that manipulate

that data, and keeps both safe from outside interference and misuse. In other words, it's a way to
hide the implementation details of an object from the outside world and only expose the necessary

information through public methods.

public class BankAccount {


private double balance;
public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}
public double getBalance() {
return balance;
}

public static void main(String[] args) {


BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Balance: " + account.getBalance());
}
}

3. Java Polymorphism
Polymorphism is a concept in Java that allows objects of different classes to be treated
as objects of a common superclass. This means that objects of different classes can be
used interchangeably, as long as they share a common interface or superclass.
Polymorphism allows for more flexibility and generic code, making it easier to write programs that
can work with different types of objects.
public class Animal {
public void sound() {
System.out.println("The animal makes a sound");
}
}

public class Dog extends Animal {


@Override
public void sound() {
System.out.println("The dog barks");
}
}

public class Cat extends Animal {


public void sound() {
System.out.println("The cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();

animal.sound();
dog.sound();
cat.sound();
}
}

4. Java Inheritance
Inheritance is a mechanism in Java that allows one class to inherit the properties and behavior
of another class. The class that is being inherited from is called the superclass or parent class,
and the class that is doing the inheriting is called the subclass or child class.

Super Class:

A super class is a class that is being inherited from. It provides the common attributes and methods

that can be shared by multiple subclasses.

Sub Class:

A sub class is a class that inherits from a super class. It inherits all the attributes and methods of the

super class and can also add new attributes and methods or override the ones inherited from the

super class.
// Super class

class Animal {

void sound() {

System.out.println("The animal makes a sound");

// Sub class

class Dog extends Animal {

void sound() {

System.out.println("The dog barks");

public class InheritanceExample {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.sound(); // Output: The dog barks

Overriding:

Overriding is a mechanism in Java that allows a sub class to provide a specific implementation for a

method that is already defined in its super class. The method in the sub class has the same name,

return type, and parameter list as the method in the super class, but it can have a different

implementation.
// Super class

class Shape {

void draw() {

System.out.println("Drawing a shape");

// Sub class

class Circle extends Shape {

void draw() {

System.out.println("Drawing a circle");

public class OverridingExample {

public static void main(String[] args) {

Circle myCircle = new Circle();

myCircle.draw(); // Output: Drawing a circle

Overloading:

Overloading is a mechanism in Java that allows multiple methods with the same name to be defined, as
long as they have different parameter lists. This allows for more flexibility in method calls, as the correct
method to call can be determined based on the number and types of arguments passed.
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class OverloadingExample {


public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(2, 3)); // Output: 5
System.out.println(calculator.add(2.5, 3.5)); // Output: 6.0
System.out.println(calculator.add(2, 3, 4)); // Output: 9
}
}

Defining Package:
In Java, a package is a way to group related classes and interfaces together. A package is defined using
the package keyword followed by the name of the package.

For example: package com.example.myapp;

This defines a package named com.example.myapp. All classes and interfaces in this file will be part of
this package.
CLASSPATH Setting for Packages:

The CLASSPATH environment variable tells Java where to find the classes and packages. To use a package,
you need to set the CLASSPATH to include the directory where the package is located.

For example, if you have a package com.example.myapp in a directory C:\MyApp, you would set
the CLASSPATH as follows:

set CLASSPATH=C:\MyApp

Alternatively, you can use the -cp or -classpath option when compiling or running your Java program:
javac -cp C:\MyApp MyProgram.java
java -cp C:\MyApp MyProgram

Making JAR Files for Library Packages:

A JAR (Java Archive) file is a way to package multiple classes and resources into a single file. To create a JAR
file, you can use the jar command:

jar cvf myapp.jar com/example/myapp/*.class

This creates a JAR file named myapp.jar that contains all the classes in the com.example.myapp package.

To use a JAR file, you need to add it to the CLASSPATH. For example:

set CLASSPATH=C:\MyApp\myapp.jar

Import and Static Import:

To use a class or interface from a package, you need to import it using the import statement. For example:

import com.example.myapp.MyClass;

This imports the MyClass class from the com.example.myapp package.

You can also use static import to import static members of a class. For example:

import static com.example.myapp.MyClass.MY_CONSTANT;

This imports the MY_CONSTANT static variable from the MyClass class.
Naming Convention for Packages:

The naming convention for packages is to use a reverse domain name format, such
as com.example.myapp. This helps to avoid naming conflicts and makes it easier to identify the origin of
the package.

Here are some best practices for naming packages:

 Use a reverse domain name format (e.g. com.example.myapp)


 Use lowercase letters and avoid underscores
 Keep the package name short and descriptive
 Avoid using abbreviations or acronyms unless they are widely recognized

By following these conventions, you can create packages that are easy to use and maintain.

You might also like