UNIT-1 Introduction To OOP and Java
UNIT-1 Introduction To OOP and Java
by
S.Sakkaravarthi, AP/IT
Ramco Institute of Technology, Rajapalayam
Programming Paradigms
◆ procedural programming paradigm characterizes a program as a series of linear steps (that is, code).
This process-oriented model can be thought of as code acting on data. Example: C Programming
language
◆ An object can be defined as a data field that has unique attributes and behavior.
OOP-Contd
Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined
interfaces to that data. An object oriented program can be characterized as data controlling access to code.
In other words, Object Oriented Programming Paradigm can be defined as a programming model which is
based upon the concept of objects. Objects contain data in the form of attributes and code in the form of
methods.
For example, dogs have states or data members like color, breed, and the behaviors or methods (actions they
can perform) are barking, wagging their tail, eating, sleeping, etc.
Difference between Procedure Oriented & Object Oriented
Programming Object Oriented Programming
Procedure Oriented Programming
1 program is divided into small parts called functions. program is divided into parts called objects.
2 Importance is not given to data but to functions as well as Importance is given to the data rather than procedures
sequence of actions to be done. or functions because it works as a real world.
4 It does not have any access specifier. Data can move freely OOP has access specifiers named Public, Private,
from Protected, etc.
function to function in the system.
5 Data can move freely from function to function in the system. objects can move and communicate with each
other through member functions.
6 To add new data and function in POP is not so easy. OOP provides an easy way to add new data and
function.
7 Most function uses Global data for sharing that can be In OOP, data can not move easily function to
accessed freely from function to function in the system. function, it can be kept public or private so we can
control the access of data.
8 It does not have any proper way for hiding data so it is less OOP provides Data Hiding so provides more security
secure.
9 Overloading is not possible. In OOP, overloading is possible in the form
of Method Overloading and Method
Overriding.
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. Thus, a class is a logical construct. It can't be physical. Only object has physical reality.
Syntax
class <class_name>
field;
method;
}
What is an Object?
Con…
class House {
String address;
String color;
double area;
void openDoor() {
//Write
code here
}
void closeDoor() {
//Write
code here
}
... ...
}
Object Oriented Programming features
Abstraction Encapsulation
Inheritance Polymorphism
Abstractio
n
• One of the most fundamental concept of OOPs is Abstraction.
• Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.
• For example:
• when you login to your Amazon account online, you enter your
user_id and password and press login, what happens when you
press login, how the input data sent to amazon server, how it gets
verified is all abstracted away from the you.
Abstraction
Con…
• Another example of abstraction:
• A car in itself is a well-defined object, which is composed of several other
smaller objects like a gearing system, steering mechanism, engine, which are
again have their own subsystems. But for humans car is a one single object,
which can be managed by the help of its subsystems, even if their inner
details are unknown.
Object Oriented Programming features
Abstraction Encapsulation
Inheritance Polymorphism
Encapsulatio
n
• Encapsulation simply means binding object state(fields) and
behavior(methods) together. If you are creating class, you are doing
encapsulation.
• Encapsulation is:
• Binding the data with the code that manipulates it.
• It keeps the data and the code safe from external interference
Object Oriented Programming features
Abstraction Encapsulation
Inheritance Polymorphism
Inheritance
• Inheritance is the mechanism by which an object acquires the
some/all properties of another object.
• The process by which one class acquires the properties(data
members) and functionalities(methods) of another class is called
inheritance.
Inheritance
• The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common
properties and functionalities can be extended from the another
class.
Inheritance
• Inheritance is a process of defining a new class based on an existing
class by extending its common data members and methods.
• Inheritance allows us to reuse of code, it improves reusability in your
java application.
• Note: The biggest advantage of Inheritance is that the code that is
already present in base class need not be rewritten in the child class.
Types of Inheritance
Example Program-Single Level Inheritance
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();
}
Output:
barking…
Eating…
Child and Base
Class
• Child Class:
• The class that extends the features of another class is known as child class,
sub class or derived class.
• Parent Class:
• The class whose properties and functionalities are used(inherited) by
another class is known as parent class, super class or Base class.
• Note: The derived class inherits all the members and methods that
are declared as public or protected.
Types of inheritance
• Single Inheritance: refers to a child and parent class relationship where a
class extends the another class.
• Multilevel inheritance: refers to a child and parent class relationship where
a class extends the child class. For example class C extends class B and class
B extends class A.
• Hierarchical inheritance: refers to a child and parent class relationship
where more than one classes extends the same class. For example, classes
B, C & D extends the same class A.
• Multiple Inheritance: refers to the concept of one class extending more
than one classes, which means a child class has two parent classes. For
example class C extends both classes A and B. Java doesn’t support
multiple inheritance
Object Oriented Programming features
Abstraction Encapsulation
Inheritance Polymorphism
Polymorphis
m
• Polymorphism is one of the OOPs feature that allows us to perform a
single action in different ways.
It helps in data hiding, keeping the data and information safe from leaking or
exposure.
Because OOPs provide reusability to the code, we can use a class many times.
In OOPs, it is easy to maintain code as there are classes and objects, which help
in making it easy to maintain rather than restructure.
Java Buzzword
The features of Java are also known as Java buzzwords. The primary objective of Java
programming language creation was to make it portable, simple and secure programming language. A list of the
most important features of the Java language is given below.
I) Simple
II) Object Oriented
III) Portable
IV) Platform Independent
V) Secured
VI) Robust
VII)Architecture Neutral
VIII)Interpreted & High Performance
IX) Distributed
X) Dynamic
XI) Multithreaded
Java-Simple
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.
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.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
Java-Platform Independent
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 (class file)
This bytecode or class file is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Java-Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
No explicit pointer
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.
Java-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.
Java-Interpreted & 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.
Java-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.
Java-Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand.
Java supports dynamic compilation and automatic memory management (garbage collection).
Java-Multithreading
Multithreaded
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.
System.out.println(“HELLOWORLD!”);
Output: HELLOWORLD!
Compilation Flow
When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.
At Runtime Flow, the following steps are performed
Explanation
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.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method. The
main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method.
So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
Defining Classes in java
A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class
keyword
Syntax:
class classname {
type instance- variable1;
type instance- variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
...
type methodnameN(parameter-list) {
// body of method
}
Declaring Objects
First, declare a variable of the class type. This variable does not define an object. Instead, it is simply a
variable that can refer to an object.
Second, acquire an actual, physical copy of the object and assign it to that variable. This is done using
the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Syntax:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Declaring Objects –
contd…
The first line declares mybox as a reference to an object of type Box. At this point, mybox does not
yet refer to an actual object. The next line allocates an object and assigns a reference to it to
mybox.
After the second line executes, we can use mybox as if it were a Box object. But in reality,
mybox simply holds, in essence, the memory address of the actual Box object.
Java Program using class and objects
class Box
double width;
double height;
double depth;
double vol;
mybox.height = 20;
mybox.depth = 15;
Constructor is a special type of method having the same name as class name and it 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.
2. Parameterized constructor
}
}
Default Constructor
Example of default-constructor:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
1. //Java Program to create and call a default constructor
2. class Bike1{
3. Bike1() //creating a default constructor
4. {
5. System.out.println("Bike is created");
6. }
7. public static void main(String args[]) //main method
8. {
9. //calling a default constructor
10. Bike1 b=new Bike1();
11. }
12. }
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
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: Public, Private, Protected and Default
Method in Java
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.
Method in Java
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.
Types of Method:
There are two types of methods in Java:
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.
Built-in Method Example Program
1. public class Demo
2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
Output:
A constructor is used to initialize the state of an object. A method is used to expose the behavior of an
object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you don't have any The method is not provided by the compiler in
constructor in a class. any case.
The constructor name must be same as the class name. The method name may or may not be same as
the class name.
Access Specifier
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private-Access Specifier
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
}
Default-Access Specifier
1. package pack;
2. class A{
3. void msg(){System.out.println("Hello");}
4. }
5. //save by B.java
6. package mypack;
7. import pack.*;
8. class B{
9. public static void main(String args[]){
10. A obj = new A();//Compile Time Error
11. obj.msg();//Compile Time Error
12. }
13. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
Protected-Access Specifier
The protected access modifier is accessible within package and outside the package but through inheritance
only.
//save by A.java
package pack;
public class A
{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
1. package mypack;
2. import pack.*;
3. class B extends A{
4. public static void main(String args[]){
5. B obj = new B();
6. obj.msg();
7. }
8. } OUTPUT:Hello
Public-Access Specifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
//save by B.java
6. package mypack;
7. import pack.*;
8.
9. class B{
10. public static void main(String args[]){
11. A obj = new A();
12. obj.msg();
13. } }
Output: Hello
RECAP
A constructor must not have a return A method must have a return type.
type.
The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Access Specifier/Access Modifier
1. private
2. default
3. protected
4. public
Access Specifier
Members private default protected public
of Java
class N Y N Y
variable Y Y Y Y
method Y Y Y Y
constructor Y Y Y Y
interface N Y N Y
Access Specifier
Access within within outside package outside
Modifier class package by subclass only package
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
Private-Access Specifier
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
class A
class B
{
{
void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A(); //Compile Time Error
}
obj.msg(); //Compile Time Error
}
}
}
Protected -Access Specifier
The protected access specifier is accessible within package and
outside the package but through inheritance only.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B extends A
{
{
protected void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
B obj=new B();
}
obj.msg(); Output: Hello
}
}
}
Public -Access Specifier
The public access specifier is accessible everywhere. It has
the widest scope among all other modifiers.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B
{
{
public void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A();
}
obj.msg(); Output: Hello
}
}
}
Static Members
The static keyword in Java is used for memory management
mainly
The static keyword can be applied to a Variable, Methods,
blocks and nested classes
The static variable gets memory only once in the class area at
the time of class loading.
Advantage of Static Variable
The static method can not use non static data member or
call non-static method directly
Static
{
System.out.println(“static block is invoked”); OUTPUT:
}
static block is executed
public static void main(String args[]) Hello Main
{
System.out.println(“Hello Main”);
}
}
Difference between Instance Variable and Static
Instance Variable variable Static Variable
Each object will have its own copy of instance Only one copy of a static variable per class
variable. irrespective of how many objects created.
Changes made in an instance variable using In case of static changes will be reflected in
one object will not be reflected in other other objects as static variables are
objects as each object has its own copy of common to all object
instance variable. of a class.
Instance variable can be accessed through Static Variables can be accessed directly
object references. using class name.
class Hello class Hello
{ {
int a; static int a;
} }
Java Doc Comments
Documentation Comment
Single Line Comment
Syntax
Syntax
/* This is
Multiline comment
*/
Multi Line Comment
Syntax
/* This is
Multiline comment
*/
Documentation Comment
Documentation comments are usually used to write
large programs for a project or software application as
it helps to create documentation API