SlideShare a Scribd company logo
1 of 38
Object-Oriented Programming
in Java
Elizabeth Alexander
Hindustan University
JAVA- OBJECTS & CLASSES
● Java is an Object-Oriented Language.
● Java supports the following fundamental concepts:
■ Polymorphism
■ Inheritance
■ Encapsulation
■ Abstraction
■ Classes
■ Objects
■ Instance
■ Method
■ Message Passing
JAVA OBJECTS & CLASSES
● Object − Objects have states and behaviors
● Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// …
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// …
type methodnameN(parameter-list) {
// body of method
}
}
JAVA CLASS
A class can contain any of the following variable types.
● Local variables − Variables defined inside methods, constructors or blocks are
called local variables.
● The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
● Instance variables − Instance variables are variables within a class but outside
any method.
● These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or
blocks of that particular class.
● Class variables − Class variables are variables declared within a class, outside
any method, with the static keyword.
CREATING AN OBJECT
There are three steps when creating an object from a class −
● Declaration − A variable declaration with a variable name with an object type.
● Instantiation − The 'new' keyword is used to create the object.
● Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
DEFINING METHODS
The general form of a method:
type name(parameter-list) {
// body of method
}
● type specifies the type of data returned by the method
● The name of the method is specified by name. This can be any legal identifier
● The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed
to the method when it is called.
● If the method has no parameters, then the parameter list will be empty.
ACCESSING INSTANCE VARIABLES AND METHODS
● Instance variables and methods are accessed via created objects.
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
INITIALIZING OBJECT IN JAVA
● There are 3 ways to initialize object in java.
1. By reference variable
2. By method
3. By constructor
1. Initialization through reference
● Initializing object simply means storing data into object
● Multiple objects can be created and store information in it through reference
variable.
2.Initialization through method
● initializing the objects by invoking the method
INITIALIZING OBJECT IN JAVA Cont...
DIFFERENT WAYS TO CREATE AN OBJECT IN JAVA
There are many ways to create an object in java. They are:
● By new keyword
● By newInstance() method
● By clone() method
● By deserialization
● By factory method etc.
Anonymous object
● Anonymous simply means nameless.
● An object which has no reference is known as anonymous object.
● It can be used at the time of object creation only.
● If you have to use an object only once, anonymous object is a good approach
Anonymous object
● Example:
new Calculation();//anonymous object
● Calling method through reference:
Calculation c=new Calculation();
c.fact(5);
● Calling method through anonymous object
new Calculation().fact(5);
Creating multiple objects by one type only
● We can create multiple objects by one type only as we do in case of
primitives.
● Initialization of primitive variables:
int a=10, b=20;
● Initialization of refernce variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two
objects
CREATING OBJECTS
CONSTRUCTORS
● Every class has a constructor.
● If we do not explicitly write a constructor for a class, the Java compiler builds
a default constructor for that class.
● Each time a new object is created, at least one constructor will be invoked.
● The main rule of constructors is that they should have the same name as the
class. A class can have more than one constructor.
OOP PRINCIPLES
Encapsulation
● Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse
● Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit.
● In encapsulation, the variables of a class will be hidden from other classes, and
can be accessed only through the methods of their current class. Therefore, it is
also known as data hiding.
To achieve encapsulation in Java −
● Declare the variables of a class as private.
● Provide public setter and getter methods to modify and view the variables
values.
INHERITANCE
● Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another.
● The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
extends Keyword
● extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
POLYMORPHISM
● Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object.
THE JAVA CLASS LIBRARY
● The Java Class Library (JCL) is a set of dynamically loadable libraries that Java
applications can call at run time.
● Because the Java Platform is not dependent on a specific operating system,
applications cannot rely on any of the platform-native libraries.
● Instead, the Java Platform provides a comprehensive set of standard class
libraries, containing the functions common to modern operating systems.
● The Java environment relies on several built-in class libraries that contain many
built-in methods that provide support for such things as I/O, string handling,
networking,and graphics.
● The standard classes also provide support for windowed output. Thus, Java as a
totality is a combination of the Java language itself, plus its standard classes
● Two of Java’s built-in methods: println( ) are members of the System class,which
is a class predefined by Java that is automatically included in your programs
“this” KEYWORD
● A method will need to refer to the object that invoked it.
● “This” can be use inside any method to refer to current object.
● “This” is always reference to the object on which the method was invoked.
● this is a keyword in Java which is used as a reference to the object of the
current class, with in an instance method or a constructor.
● Using this you can refer the members of a class such as constructors,
variables and methods.
Note: The keyword this is used only within instance methods or constructors
“this” KEYWORD Cont...
In general, the keyword this is used to −
● Differentiate the instance variables from local variables if they have same names,
within a constructor or a method.
Example:
class Student {
int age;
Student(int age) {
this.age = age;
}
}
“this” KEYWORD Cont...
● Call one type of constructor (parameterized constructor or default) from other in a
class. It is known as explicit constructor invocation.
Example
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
AUTOMATIC GARBAGE COLLECTION
● The garbage collector is a program which runs on the Java Virtual Machine which
gets rid of objects which are not being used by a Java application anymore. It is a
form of automatic memory management.
● In java, garbage means unreferenced objects.
● Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
● To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
● It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
● It is automatically done by the garbage collector(a part of JVM) so we don't need
to make extra efforts.
AUTOMATIC GARBAGE COLLECTION Cont...
How can an object be unreferenced?
There are many ways:
● By nulling the reference
● By assigning a reference to another
● By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
new Employee();
The finalize( ) Method
● Sometimes an object will need to perform some action when it is destroyed.
● To handle such situations, Java provides a mechanism called finalization. By
using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector
● To add a finalizer to a class, you simply define the finalize( ) method. The Java
run time calls that method whenever it is about to recycle an object of that class.
● Inside the finalize( ) method, you will specify those actions that must be performed
before an object is destroyed.
● The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
Right before an asset is freed,the Java run time calls the finalize( ) method on the
object.
The finalize( ) Method Cont...
● The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
● Here, the keyword protected is a specifier that prevents access to finalize( ) by
code defined outside its class
● finalize( ) is only called just prior to garbage collection.
● It is not called when an object goes out-of-scope, for example. This means that
you cannot know when—or even if—finalize( ) will be executed. Therefore, your
program should provide other means of releasing system resources, etc., used by
the object.
● It must not rely on finalize( ) for normal program operation.
gc() METHOD
● The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note:
● The Garbage collector of JVM collects only those objects that are created by
new keyword. So if you have created any object without new, you can use
finalize method to perform cleanup processing (destroying remaining objects).
Java - Arrays
● Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. Array is a collection of variables of the
same type.
● Instead of declaring individual variables, such as number0, number1, ..., and
number99, one array variable can be declared such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
One-Dimensional Arrays
Declaring Array Variables
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Java - Arrays Cont...
Creating Arrays
Syntax: arrayRefVar = new dataType[arraySize];
The above statement does two things −
● It creates an array using new dataType[arraySize].
● It assigns the reference of the newly created array to the variable arrayRefVar.
dataType[] arrayRefVar = new dataType[arraySize];
● Declaring an array variable, creating an array, and assigning the reference of the
array to the variable can be combined in one statement
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
● The array elements are accessed through the index. Array indices are 0-based;
that is, they start from 0 to arrayRefVar.length-1.
Example
double[] myList = new double[10];
Java - Arrays Cont...
Returning an Array from a Method
● A method may also return an array.
Multidimensional Arrays
● In Java, multidimensional arrays are actually arrays of arrays
● To declare a multidimensional array variable, specify each additional
index using another set of square brackets
■ int twoD[][] = new int[4][5];
Arrays of Characters
● Char arrays. Strings are immutable: they cannot be changed in place or added
to. With char arrays, we manipulate character buffers.
● Performance advantages. Char arrays are faster—we can change text data
without allocations. With the String constructor, we can convert back into a string.
Java - Arrays Cont...
Java - Arrays Cont...
Processing Arrays
● When processing array elements, we often use either for loop or foreach loop
because all of the elements in an array are of same type and size of the array is
known
The foreach Loops
● JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop,
which enables you to traverse the complete array sequentially without using an
index variable.
Passing Arrays to Methods
● Just as you can pass primitive type values to methods, you can also pass arrays
to methods.
Java - Strings Class
● Strings, which are widely used in Java programming, are a sequence of
characters
● Java String class provides a lot of methods to perform operations on string such
as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
Creating Strings
CharSequence Interface
● The CharSequence interface is used to represent sequence of characters. It is
implemented by String, StringBuffer and StringBuilder classes. It means, we can
create string in java by using these 3 classes.
Java - Strings Class Cont...
● The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and
StringBuilder classes.
What is String in java
● Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create
string object.
How to create String object?
There are two ways to create String object:
1. By string literal
2. By new keyword
Java - Strings Class Cont...
1) String Literal
● Java String literal is created by using double quotes
String s="welcome";
● Each time you create a string literal, the JVM checks the string constant pool
first. If the string already exists in the pool, a reference to the pooled instance
is returned. If string doesn't exist in the pool, a new string instance is created
and placed in the pool.
String s1="Welcome";
String s2="Welcome";//will not create new instance
Java - Strings Class Cont...
Java - Strings Class Cont...
Java - Strings Class Cont...
● In the above example only one object will be created.
● Firstly JVM will not find any string object with the value "Welcome" in string
constant pool, so it will create a new object.
● After that it will find the string with the value "Welcome" in the pool, it will not
create new object but will return the reference to the same instance.
Why java uses concept of string literal?
● To make Java more memory efficient (because no new objects are created if
it exists already in string constant pool).
2) By new keyword
● String s=new String("Welcome");//creates two objects and one reference
variable
● In such case, JVM will create a new string object in normal(non pool) heap
memory and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in heap(non pool).
Java String class methods
● The java.lang.String class provides many useful methods to perform
operations on sequence of char values.
Java - Strings Class Cont...
Java StringBuffer class
● Java StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it
can be changed.
Important Constructors of StringBuffer class
1. StringBuffer() :creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str) :creates a string buffer with the specified string.
3. StringBuffer(int capacity) :creates an empty string buffer with the specified
capacity as length.
What is mutable string
● A string that can be modified or changed is known as mutable string.
StringBuffer and StringBuilder classes are used for creating mutable string.
Java StringBuilder Class
● The java.lang.StringBuilder class is mutable sequence of characters. This
provides an API compatible with StringBuffer, but with no guarantee of
synchronization.
Class constructors
● StringBuilder() : This constructs a string builder with no characters in it and
an initial capacity of 16 characters.
● StringBuilder(CharSequence seq) : This constructs a string builder that
contains the same characters as the specified CharSequence.
● StringBuilder(int capacity) : This constructs a string builder with no
characters in it and an initial capacity specified by the capacity argument.
● StringBuilder(String str) : This constructs a string builder initialized to the
contents of the specified string

More Related Content

What's hot

Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in JavaOblivionWalker
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingAmit Soni (CTFL)
 
JVM Memory Management Details
JVM Memory Management DetailsJVM Memory Management Details
JVM Memory Management DetailsAzul Systems Inc.
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.Bhautik Jethva
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 

What's hot (20)

Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Java program structure
Java program structureJava program structure
Java program structure
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
JVM Memory Management Details
JVM Memory Management DetailsJVM Memory Management Details
JVM Memory Management Details
 
Oop java
Oop javaOop java
Oop java
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java I/O
Java I/OJava I/O
Java I/O
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
History of java'
History of java'History of java'
History of java'
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 

Similar to Object oriented programming in java

Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | BasicsHùng Nguyễn Huy
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15myrajendra
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2Usman Mehmood
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 

Similar to Object oriented programming in java (20)

Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | Basics
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
oop 3.pptx
oop 3.pptxoop 3.pptx
oop 3.pptx
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 

More from Elizabeth alexander (11)

Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Java applet
Java appletJava applet
Java applet
 
Io streams
Io streamsIo streams
Io streams
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Quantitative Aptitude- Number System
Quantitative Aptitude- Number SystemQuantitative Aptitude- Number System
Quantitative Aptitude- Number System
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 

Recently uploaded

Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 

Recently uploaded (20)

Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 

Object oriented programming in java

  • 1. Object-Oriented Programming in Java Elizabeth Alexander Hindustan University
  • 2. JAVA- OBJECTS & CLASSES ● Java is an Object-Oriented Language. ● Java supports the following fundamental concepts: ■ Polymorphism ■ Inheritance ■ Encapsulation ■ Abstraction ■ Classes ■ Objects ■ Instance ■ Method ■ Message Passing
  • 3. JAVA OBJECTS & CLASSES ● Object − Objects have states and behaviors ● Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. The General Form of a Class class classname { type instance-variable1; type instance-variable2; // … type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // … type methodnameN(parameter-list) { // body of method } }
  • 4. JAVA CLASS A class can contain any of the following variable types. ● Local variables − Variables defined inside methods, constructors or blocks are called local variables. ● The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. ● Instance variables − Instance variables are variables within a class but outside any method. ● These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. ● Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
  • 5. CREATING AN OBJECT There are three steps when creating an object from a class − ● Declaration − A variable declaration with a variable name with an object type. ● Instantiation − The 'new' keyword is used to create the object. ● Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
  • 6. DEFINING METHODS The general form of a method: type name(parameter-list) { // body of method } ● type specifies the type of data returned by the method ● The name of the method is specified by name. This can be any legal identifier ● The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. ● If the method has no parameters, then the parameter list will be empty.
  • 7. ACCESSING INSTANCE VARIABLES AND METHODS ● Instance variables and methods are accessed via created objects. /* First create an object */ ObjectReference = new Constructor(); /* Now call a variable as follows */ ObjectReference.variableName; /* Now you can call a class method as follows */ ObjectReference.MethodName();
  • 8. INITIALIZING OBJECT IN JAVA ● There are 3 ways to initialize object in java. 1. By reference variable 2. By method 3. By constructor 1. Initialization through reference ● Initializing object simply means storing data into object ● Multiple objects can be created and store information in it through reference variable. 2.Initialization through method ● initializing the objects by invoking the method
  • 9. INITIALIZING OBJECT IN JAVA Cont...
  • 10. DIFFERENT WAYS TO CREATE AN OBJECT IN JAVA There are many ways to create an object in java. They are: ● By new keyword ● By newInstance() method ● By clone() method ● By deserialization ● By factory method etc. Anonymous object ● Anonymous simply means nameless. ● An object which has no reference is known as anonymous object. ● It can be used at the time of object creation only. ● If you have to use an object only once, anonymous object is a good approach
  • 11. Anonymous object ● Example: new Calculation();//anonymous object ● Calling method through reference: Calculation c=new Calculation(); c.fact(5); ● Calling method through anonymous object new Calculation().fact(5); Creating multiple objects by one type only ● We can create multiple objects by one type only as we do in case of primitives. ● Initialization of primitive variables: int a=10, b=20; ● Initialization of refernce variables: Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects CREATING OBJECTS
  • 12. CONSTRUCTORS ● Every class has a constructor. ● If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. ● Each time a new object is created, at least one constructor will be invoked. ● The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
  • 13. OOP PRINCIPLES Encapsulation ● Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse ● Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. ● In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. To achieve encapsulation in Java − ● Declare the variables of a class as private. ● Provide public setter and getter methods to modify and view the variables values.
  • 14. INHERITANCE ● Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. ● The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). extends Keyword ● extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Syntax class Super { ..... ..... } class Sub extends Super { ..... ..... }
  • 15. POLYMORPHISM ● Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
  • 16. THE JAVA CLASS LIBRARY ● The Java Class Library (JCL) is a set of dynamically loadable libraries that Java applications can call at run time. ● Because the Java Platform is not dependent on a specific operating system, applications cannot rely on any of the platform-native libraries. ● Instead, the Java Platform provides a comprehensive set of standard class libraries, containing the functions common to modern operating systems. ● The Java environment relies on several built-in class libraries that contain many built-in methods that provide support for such things as I/O, string handling, networking,and graphics. ● The standard classes also provide support for windowed output. Thus, Java as a totality is a combination of the Java language itself, plus its standard classes ● Two of Java’s built-in methods: println( ) are members of the System class,which is a class predefined by Java that is automatically included in your programs
  • 17. “this” KEYWORD ● A method will need to refer to the object that invoked it. ● “This” can be use inside any method to refer to current object. ● “This” is always reference to the object on which the method was invoked. ● this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. ● Using this you can refer the members of a class such as constructors, variables and methods. Note: The keyword this is used only within instance methods or constructors
  • 18. “this” KEYWORD Cont... In general, the keyword this is used to − ● Differentiate the instance variables from local variables if they have same names, within a constructor or a method. Example: class Student { int age; Student(int age) { this.age = age; } }
  • 19. “this” KEYWORD Cont... ● Call one type of constructor (parameterized constructor or default) from other in a class. It is known as explicit constructor invocation. Example class Student { int age Student() { this(20); } Student(int age) { this.age = age; } }
  • 20. AUTOMATIC GARBAGE COLLECTION ● The garbage collector is a program which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management. ● In java, garbage means unreferenced objects. ● Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. ● To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management. Advantage of Garbage Collection ● It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory. ● It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
  • 21. AUTOMATIC GARBAGE COLLECTION Cont... How can an object be unreferenced? There are many ways: ● By nulling the reference ● By assigning a reference to another ● By annonymous object etc. 1) By nulling a reference: Employee e=new Employee(); e=null; 2) By assigning a reference to another: Employee e1=new Employee(); Employee e2=new Employee(); e1=e2;//now the first object referred by e1 is available for garbage collection 3) By annonymous object: new Employee();
  • 22. The finalize( ) Method ● Sometimes an object will need to perform some action when it is destroyed. ● To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector ● To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. ● Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. ● The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed,the Java run time calls the finalize( ) method on the object.
  • 23. The finalize( ) Method Cont... ● The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } ● Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class ● finalize( ) is only called just prior to garbage collection. ● It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. ● It must not rely on finalize( ) for normal program operation.
  • 24. gc() METHOD ● The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes. public static void gc(){} Note: ● The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
  • 25. Java - Arrays ● Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. Array is a collection of variables of the same type. ● Instead of declaring individual variables, such as number0, number1, ..., and number99, one array variable can be declared such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. One-Dimensional Arrays Declaring Array Variables dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.
  • 26. Java - Arrays Cont... Creating Arrays Syntax: arrayRefVar = new dataType[arraySize]; The above statement does two things − ● It creates an array using new dataType[arraySize]. ● It assigns the reference of the newly created array to the variable arrayRefVar. dataType[] arrayRefVar = new dataType[arraySize]; ● Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, ..., valuek}; ● The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
  • 27. Example double[] myList = new double[10]; Java - Arrays Cont...
  • 28. Returning an Array from a Method ● A method may also return an array. Multidimensional Arrays ● In Java, multidimensional arrays are actually arrays of arrays ● To declare a multidimensional array variable, specify each additional index using another set of square brackets ■ int twoD[][] = new int[4][5]; Arrays of Characters ● Char arrays. Strings are immutable: they cannot be changed in place or added to. With char arrays, we manipulate character buffers. ● Performance advantages. Char arrays are faster—we can change text data without allocations. With the String constructor, we can convert back into a string. Java - Arrays Cont...
  • 29. Java - Arrays Cont... Processing Arrays ● When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of same type and size of the array is known The foreach Loops ● JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. Passing Arrays to Methods ● Just as you can pass primitive type values to methods, you can also pass arrays to methods.
  • 30. Java - Strings Class ● Strings, which are widely used in Java programming, are a sequence of characters ● Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. Creating Strings
  • 31. CharSequence Interface ● The CharSequence interface is used to represent sequence of characters. It is implemented by String, StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes. Java - Strings Class Cont...
  • 32. ● The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes. What is String in java ● Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object. How to create String object? There are two ways to create String object: 1. By string literal 2. By new keyword Java - Strings Class Cont...
  • 33. 1) String Literal ● Java String literal is created by using double quotes String s="welcome"; ● Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. String s1="Welcome"; String s2="Welcome";//will not create new instance Java - Strings Class Cont...
  • 34. Java - Strings Class Cont...
  • 35. Java - Strings Class Cont... ● In the above example only one object will be created. ● Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. ● After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance. Why java uses concept of string literal? ● To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
  • 36. 2) By new keyword ● String s=new String("Welcome");//creates two objects and one reference variable ● In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool). Java String class methods ● The java.lang.String class provides many useful methods to perform operations on sequence of char values. Java - Strings Class Cont...
  • 37. Java StringBuffer class ● Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. Important Constructors of StringBuffer class 1. StringBuffer() :creates an empty string buffer with the initial capacity of 16. 2. StringBuffer(String str) :creates a string buffer with the specified string. 3. StringBuffer(int capacity) :creates an empty string buffer with the specified capacity as length. What is mutable string ● A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.
  • 38. Java StringBuilder Class ● The java.lang.StringBuilder class is mutable sequence of characters. This provides an API compatible with StringBuffer, but with no guarantee of synchronization. Class constructors ● StringBuilder() : This constructs a string builder with no characters in it and an initial capacity of 16 characters. ● StringBuilder(CharSequence seq) : This constructs a string builder that contains the same characters as the specified CharSequence. ● StringBuilder(int capacity) : This constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. ● StringBuilder(String str) : This constructs a string builder initialized to the contents of the specified string