Object Oriented Programming Structure - Features of OOPS: Objects / Instance Classes Inheritance Polymorphism
Object Oriented Programming Structure - Features of OOPS: Objects / Instance Classes Inheritance Polymorphism
Note:
• Local variables require explicit initialization.
• Instance variables are initialized automatically.
Variable Initialization
Variable Value
• byte 0
• short 0
• int 0
• long 0L
• float 0.0F
• double 0.0D
• char '\u0000'
• boolean false
• All reference types null
Constructor
• It is a Spl. Method
• Purpose: To initialize the class members
• Features:
Same name as that of the class name
No return type including VOID
Can have access specifier
Can be overloaded
Constructors are NOT inherited
Invoked automatically whenever the object is
created.
The no. of time of invocation depends on no. of
object created
Arrays
• Group data objects of the same type, in a
contiguous block of memory.
• An array is an object; it is created with new.
• Can be declared as a primitive type or Class
type.
• Array index starts with 0.
• You cannot resize an array.
• You can use the same reference variable to
refer to an entirely new array.
Array Declaration and
Instantiation
• Array declaration
<element type>[] <array name>;
int[] myArray;
• Constructing an array
<array name> =
new <element type> [<array size>];
Primitive array:
*****************
int[] myArray = { 1 , 2 , 3 , 4 , 5 } ;
Reference Array:
********************
Object[] objArr = { new Pizza(), new Pizza(), null };
Initializing an Array
• Explicit initialization can also be done using
array subscripts.
int[] myArray = new int[3];
myArray [0] = 10;
myArray [1] = 20;
myArray [2] = 30;
Inheritance
• Deriving the parent class properties and
methods to the child class.
• Types of inheritance:
Single level inheritance
- one super and one sub class
Multilevel inheritance
- The sub class of one level forms the super
class of another level
Multiple inheritance [ not supported by java]
- many super and one sub class
Hierarchical inheritance
- one super and many sub classes
Hybrid inheritance
- multiple and multi level combined.
Inheritance
• Two important concepts
Generalization - Up the hierarchy
Specialization - Down the hierarchy
• Purpose : Reusability (without changing its
identity)
• Syntax:
<modifier> class <name> extends <superclass>
{
<declaration>*
}
IS-A & HAS-A relationship
• When you want to know if one thing should
extend another, use the IS-A test.
Eg : Triangle IS-A Shape
• Do not apply inheritance if the subclass and
super class do not pass the IS-A test.
• Is-a relationship can be described in Java
keyword extends.
• The IS-A relationship – Unidirectional
IS-A & HAS-A relationship
• When two classes are related, but not through
inheritance, (for example, one class has a
reference to another class) then you say that
the two classes are joined by HAS-A
relationship.
• Has-a relationship can be described in Java
code as member fields.
Note:
• Code reuse is also best achieved by
aggregation when there is no is-a relationship
IS-A & HAS-A relationship
• class Car
{
}
class BMW extends Car => IS-A R/S
{
boolean auto_gear = “true” => Has-A R/S
}
Polymorphism
• Polymorphism (from Greek, meaning “many
forms”) is a feature that allows one interface to
be used for a general class of actions that is
one interface with multiple methods.
• Types:
Overloading => Ad-Hoc Polymorphism
- Same method name with different set of
parameters.
- Early Binding
Overriding => True polymorphism
- Same method name with same set of
parameters.
- Late Binding
Types of Overloading
• Function Overloading
• Constructor Overloading
• NO operator Overloading in Java
• Rules :
No. of parameter should change
Datatype of the parameter should change
Sequence of passing the paramter should
change.
Overriding
• The overridden method in the superclass is NOT inherited by
the subclass, and the new method in the subclass must
uphold the following rules of method overriding:
The new method definition must have the same method
signature (i.e., method name and parameters) and the
same return type.
Overridden Methods Cannot Be Less Accessible.
• A subclass cannot override fields of the superclass, but it can
hide them.
• Works only with inheritance.
• Constructors cant be Overridden.
• Super keyword is used to invoke an overridden method in the
superclass.
this() and super() call for
constructor
• this() construct is used to implement local chaining of
constructors in the class when an instance of the class is
created.
• The this() call invokes the constructor with the
corresponding parameter list.
• super() method is used to invoke the IMMEDIATE base
class constructor. This allows the subclass to influence
the initialization of its inherited state when an object of
the subclass is created.
• this() and super() call must occur as the first statement
in a constructor.
Example : this() and super()
class GParent
{
int a,b,c;
GParent() {
System.out.println("From gparent");
}
GParent(int a,int b) {
//this(a,b,100);
this();
System.out.println("a= "+a+" b = "+ b);
}
Parent(int x,int y)
{
super(x,y);
this.x=x;
this.y = y;
System.out.println("x= "+x+" y = "+ y);
}
}
Example : this() and super()
class Child extends Parent
{
Child()
{
super(23,343);
System.out.println("From child");
}
}
class SuperEx
{
public static void main(String[] a)
{
//Parent p = new Parent(12,23);
Child d = new Child();
}
instanceof operator
• Use instanceof to test the type of an object.
• Restore full functionality of an object by casting.
• Example:
public void doSomething(Employee e) {
if ( e instanceof Manager )
{
Manager m = (Manager) e;
}
// rest of operation
}
Static Keyword
• It’s a Access Modifier
• The static keyword is used as a modifier on
variables, methods, and nested classes.
• The static keyword declares the attribute or
method is associated with the class as a whole
rather than any particular instance of that class.
• Thus static members are often called class
members, such as class attributes or class
methods.
Static Keyword
• A static method can access only the static
variable. But the normal variable can access
both static and normal variable.
• Static members will get loaded into the memory
only once.
• Static members are subjected to change
common for all the instance.
• NO NEED FOR OBJECT to access the static
member.
Static Variable Example
class StatEx
{
int i=10;
static int j = 20;
//static initializer
static
{
counter=10;
System.out.println("Static block invoked "+counter);
}
public static void sMethod()
{
System.out.println("Static method" + counter++);
}
}
Static Initializer Example
class StatEx
{
public static void main(String arg[])
{
System.out.println("from main");
StatEx1.sMethod();
StatEx1.sMethod();
}
}
Final Keyword
• Variable become Constant
• Method cant be Overridden
• Class cant be inherited
• Note:
All final variable need Explicit initialization
Wrapper Class
• Conversion of primitive types to the object
equivalent done through wrapper classes.
• Allow objects to be created from primitive types.
• Wrapped values are immutable (Cant modify) .
To wrap another value, you need to create
another object.
• Wrapper class are present in java.lang package
• All the wrapper classes are declared final.
Primitive Data Types and
Corresponding Wrapper Classes
Primitive Data Type Wrapper Class Constructor Arguments
boolean Boolean boolean or String
int x=10;
Integer n = new Integer(x); //Boxing
int y = n.intValue(); //UnBoxing
AutoBoxing and AutoUnboxing
Example:
int x=10;
Integer n = x; //AutoBoxing
int y = n; //AutoUnBoxing
Methods to Extract the Wrapped
Values
Method Class
public boolean booleanValue() Boolean
public char charValue() Character
public byte byteValue() Byte, Short, Integer, Long, Float,
Double
public short shortValue() Byte, Short, Integer, Long, Float,
Double
public int intValue() Byte, Short, Integer, Long, Float,
Double
public long longValue() Byte, Short, Integer, Long, Float,
Double
public float floatValue() Byte, Short, Integer, Long, Float,
Double
public double doubleValue() Byte, Short, Integer, Long, Float,
Double
Methods to Convert Strings to
Primitive Types
Wrapper Method Signature Method Arguments
Class
• Primitive parseXxx(String)
To convert a String to a primitive
• Wrapper valueOf(String)
To convert a String to a Wrapper
Object Class
• Root class of Java => Object
• equals() method = > Check only values
• toString() method =>Check value & reference
• hashCode() => return the address of the object
enum Edge
{
TOP,BOTTOM,LEFT,RIGHT
};
class MyClass
{
public static void main(String[] a)
{
Edge e = Edge.TOP;
int i = e.ordinal();
System.out.println(e);
System.out.println(i);
}
}
Enum Example2
enum Edge
{
TOP,BOTTOM,LEFT,RIGHT;
MONDAY(8,true),
TUESDAY(8,true),
WEDNESDAY(8,true),
THURSDAY(8,true),
FRIDAY(8,true),
SATURDAY(4,false),
SUNDAY(0,false);
}
Inner Class
• A class that is declared within another class or
interface, is called a nested class.
• There are four categories of nested classes
Regular class - class within the class
Method-local class – class within the method of
the outer class
Static nested class - inner classes marked with
the static modifier (top-level nested class)
Anonymous class - part of a method argument.
• All inner classes are nested classes, but not all
nested classes are inner classes.
Example for Regular InnerClass
class MyOuter
{
int x =7;
class MyInner
{
public void InnerMethod()
{
System.out.println("x == " + x);
}
}
public void OuterMethod()
{
MyInner inn = new MyInner();
inn.InnerMethod();
}
Example for Regular InnerClass
}
Method-local inner class
• A method-local inner class can be instantiated
only within the method where the inner class is
defined.
• Can access the outer class level variable.
• CANT access the variable inside the method in
which the inner class is created except a final
variable.
• Method-local inner class can be declared
abstract and final.
• method-local inner class can't use any access
specifiers.
Method-local inner class
class MouterClass
{
int x =10;
public void OuterMethod()
{
final int j=90;
class MinnerClass
{
public void minnerMethod()
{
System.out.println("Hello ..." + x + j);
}
}
MinnerClass mic = new MinnerClass();
mic.minnerMethod();
}
public static void main(String[] a)
{
MouterClass moc = new MouterClass();
moc.OuterMethod();
}
}
Static nested class
• Static nested classes are inner classes marked
with the static modifier.
• A static nested class is not an inner class, it's a
top-level nested class.
• A static nested class cannot access non-static
members of the outer class.
Static nested class
class OuterClass
{
static int i =10;
public void method()
{
System.out.println("i == " + ++i);
}
static class InnerClass
{
public void display()
{
System.out.println("i == " + i);
}
}
Static nested class
Throwable
Exception Error
Others…
Exception-handling mechanism
• Contains five keywords:
try - catch – throw - throws – finally
Method throws ExceptionName{
try{
--risky code goes here
}catch(ExceptionClassName ObjectName){
-- Exception handler block code
throw Exception_Instance //Ducking it
}
finally{
-- cleanup your code goes here
}
}
About try-catch-finally
• A try block should be followed by at least one catch
block.
• The code inside try block is called as protected code.
• Can have one or more catch block.
• If you have multiple catch block, make sure that the last
catch block contain the super most class in the hierarchy.
• You may also write an optional “finally” block. This block
contains code that is ALWAYS executed, either after the
“try” block code, or after the “catch” block code.
• The catch block may or may not contain throw keyword.
• The try block can also be nested.
Example 1
class PrintStack
{
public static void main(String args[])
{
int Num1= 30 , Num2 = 0;
try
{
int Num3=Num1/Num2;
}
catch(ArithmeticException obj)
{
System.out.println("Exception"+obj);
obj.printStackTrace();
}
}
}
Rules in Exception
• The Declare or Handle Rule
Handle the exception by using the
try-catch-finally block.
• Declare that the code causes an exception by
using the throws clause.
• You do not need to declare runtime exceptions
or errors.
• You can choose to handle runtime exceptions.
Passing the exception
In any method that might throw an exception,
you may declare the method as “throws” that
exception, and thus avoid handling the exception
yourself
Example
• public void myMethod throws IOException {
… normal code with some I/O
}
Throws clause
class UncheckedThrows
{
public void show() throws ArithmeticException
{
System.out.println("Hai I am not handled");
}
}
String Class Facts
• An object of the String class represents a string
of characters.
• The String class belongs to the java.lang
package, which does not require an import
statement.
• Like other classes, String has constructors and
methods.
• Unlike other classes, String has two operators,
+ and += (used for concatenation).
• String class is declare final , therefore
immutable.
Literal Strings
• are anonymous objects of the String class
• are defined by enclosing text in double quotes.
“This is a literal String”
• don’t have to be constructed.
• can be assigned to String variables.
• can be passed to methods and constructors as
parameters.
• have methods you can call.
Literal String Example
//assign a literal to a String variable
String name = “Priya”;
word “java"
“Java"
Empty Strings
import java.util.*;
class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
set.add("one");
set.add("second");
set.add("3rd");
set.add(new Integer(4));
set.add(new Float(5.0F));
set.add("second"); // duplicate, not added
set.add(new Integer(4)); // duplicate, not added
System.out.println(set);
}
}
Collection API - Storage
• The storage associated with any one collection can be
implemented in many ways, but the Collections API
implements the four methods that are most widely used:
Array: supports insertion, deletion, but growing the
store is more difficult.
ArrayList: grow in number of elements. Search is
faster. But not insertion and deletion. Vector(provides
synchronization)
Linked list: supports insertion, deletion, and growing
the store, but makes indexed access slower. Use
when insertions and deletions happen frequently.
Tree: supports insertion, deletion, and growing the
list. Indexed access is slow, but searching is faster.
Hash table: supports insertion, deletion, and growing
the store. Indexed access is slow, but searching is
particularly fast. However, hashing requires the use of
unique keys for storing data elements.
Set Classes
• HashSet :
provides the faster access to a data item.
no guarantee that the items will be ordered.
does not offer synchronization.
• Tree Set:
presents sorted data items.
performance is not as good as HashSet.
does not offer synchronization.
• LinkedHashSet:
Similar to HashSet that maintains a doubly linked
list.
It is an ordered collection, ordered by insertion,
but not sorted.
does not offer synchronization
Map Classes
• HashTable:
implementation is based on the hashtable data
structure.
No ordering.
implementation is synchronized
• HashMap:
based on the hashtable data structure.
No ordering
allows null and is unsynchronized
• LinkedHashMap:
maintains a doubly linked list.
• TreeMap:
implements the SortedMap interface
Sorted and unsynchronized.
Class Interface Duplicates Ordered/ Synchronized
Allowed? Sorted
ArrayList List Yes Ordered by index No
Not sorted
LinkedList List Yes Ordered by index No
Not sorted
Vector List Yes Ordered by index Yes
Not sorted
HashSet Set No Not ordered No
Not sorted
LinkedHashSet Set No Ordered by No
insertion
Not sorted
TreeSet Set No Sorted either by No
natural order or by
your comparison
rules
Class Interface Duplicates Ordered/ Synchronized
Allowed? Sorted
THREAD
THREAD
STACK
STACK
SHARED
SHARED
MEMORY
MEMORY
THREAD
THREAD
DATA
DATA
THREAD
THREAD
TEXT
TEXT
– Example:
● Two threads are ready to run
● First thread: priority of 5, already running
● Second thread = priority of 10, comes in while first
thread is running
Thread Synchronization
• Done in two ways
To method
public synchronized void method()
{ }
To block
synchronized(this)
{
}
Wait() and notify()
• Wait() and notify should be used to restrict the
thread before doing an operation without a
notification from the other thread.
• Should be used along with the synchronized
block
wait()
• When a thread enters a wait state, it does
nothing until it is notified by another thread.
• It also gives up it’s lock on the object when wait
is called.
public synchronized blah() {
wait();
… // do something
}
notify()
• To awaken a thread, a different thread which
has a lock on the same object must call notify.
• When notify is called, the block that had the
lock on the object continues to have it’s lock it
releases it.
Then a thread is awakened from its wait() and
can grab the lock and continue processing.
• There are two versions - notify() and notifyAll().
• Notify is safe only under 2 conditions:
When only 1 thread is waiting, and thus
guaranteed to be awakened.
When multiple threads are waiting on the same
condition, and it doesn’t matter which one
awakens.
• In general, use notifyAll()
Thread Group
• You can include thread in a set of threads by
adding it to an instance of ThreadGroup
• ThreadGroups can contain not only threads but
also other ThreadGroups.
Semaphore
• Semaphore is a synchronization mechanism,
which implements mutual exclusion among
processes to avoid race condition to access any
shared resource.
• Semaphore maintains a counter to implement
locking and unlocking. It avoids busy waiting. If
a critical section is in use, the calling process
will be removed from a run queue and put into a
sleep state.
• Java 5 comes with semaphore implementations
in the java.util.concurrent package so you don't
have to implement your own semaphores.
• A mutex is really a semaphore with value 1.
Semaphores
• Semaphores have two purposes
Mutex: Ensure threads don’t access critical
section at same time
Scheduling constraints: Ensure threads
execute in specific order
• A semaphore is an IPC mechanism that is
implemented conceptually with at least these
two components
– a counter (int) variable
– a wait queue of processes
• And has at least these two operation
– wait for the semaphore to be free (p)
– signal that the semaphore is now free (v)
Semaphore
• The semaphore has at least these possible
states:
Free, or available, or not in use
Not free, or unavailable, or in use
• Interpretation of the counter variable:
If the counter is positive, then the semaphore is
free.
If the counter is zero (or negative), then the
semaphore is in use (not free).
Semaphore
• Cases using a semaphore S
1. If a process does a wait (p) on S, and if the
semaphore is free, then S is decremented
(S.counter = S.counter – 1;)
2. If a process does a wait (p) on S and if S is not
free, then the process is blocked and put in S’s
wait queue.
3. If a process does a signal (v) on S and if there
is no process in the wait queue for S, then the
semaphore is set to free by incrementing its
counter (to positive).
4. If a signal (v) on S and there is a process in the
S queue, then the process at the head of the
queue is removed and unblocked (and can
continue to execute)
IOStreams
• Usual Purpose: storing data to ‘nonvolatile‘
devices, e.g. harddisk
• Classes provided by package java.io
• Data is transferred to devices by ‘streams‘
output - stream
Program Device
input - stream
Program Device
keyboard
standard
input stream
CPU
standard
output MEM
stream
monitor
terminal
console
HDD
How does information
travel across?
Streams
keyboard
standard
input stream
CPU
standard
output MEM
stream
monitor
terminal
console file
input
stream
LOAD HDD
How does information READ
travel across? file
files output
Streams stream
SAVE
WRITE
IOStreams
• JAVA distinguishes between 2 types of
streams:
• Text – streams, containing ‘characters‘
Program I ‘ M A S T R I N G \n Device
pro con
Binary Efficient in terms Preinformation
of time and space about data needed
(input to understand
content
&output
stream)
Text(reader Human readable, Not efficient
contains
and writer) redundant
information
Binary vs. TextFiles
• When use Text- / BinaryFiles ?
• ALWAYS use TextFiles for final results
• Binary Files might be used for non-final
interchange between programs
• Binary Files are always used for large amount
of data (images, videos etc.)
Serialization
• Serialization: process of saving objects to a
stream i.e. in-memory object to a byte stream.
Each object is assigned a serial number on the
stream
If the same object is saved twice, only serial
number is written out the second time
When reading, duplicate serial numbers are
restored as references to the same object
• The objects must be read from the stream in
the same order in which they were written.
Serialization
• Why isn’t everything serializable?
Memory heap
When new keyword is called memory is allocated in
the heap and returned when the reference is made
null
Stack
During method calls, objects are created for method
arguments and method variables. These objects are
created on stack.
Such objects are eligible for garbage-collection when
they go out of scope.
Garbage Collection
• Advantages of Garbage Collection :
More productivity
Program Integrity
• Finalize()
Class Object has a finalize() method.
Before gc happens the finalize() method is called
It is called only once
Finalize method can be overridden by the user.
Finalize can be used to make an object not to be
garbage collected
Classical Algorithms
• Three classical algorithms
Mark-sweep
Reference counting
Semispace
• Tweaks
Generational garbage collection (JAVA
DEFAULT)
• Out of scope
Parallel –perform GC in parallel
Concurrent –run GC at same time as app
Real-time–ensure bounded pause times
Mark-Sweep
• Start with roots
Global variables, variables on stack& in
registers
• Recursively visit every object through pointers
Markevery object we find (set mark bit)
• Everything not marked = garbage
Can then sweep heap for unmarked
objectsand free them
Annotations
• Annotations in Java is all about adding meta-
data facility to the Java Elements like
package declarations,
class,
constructors,
methods,
fields,
variables and etc
• An annotation indicates that the declared
element should be processed in some special
way by a compiler, development tool,
deployment tool, or during runtime.
• Annotations are defined using an @ syntax
Structure of Java Compiler
@NonNull
Object get() {
return field;
} Comments
}
Error
Structure of Java5 Compiler
Type Annotation Class File
Parser Checker Checker Writer
Source File
class C { Class
@NonNull
Object field; File
C(@NonNull
Object p) {
field = p;
}
@NonNull
Object get() {
return field;
}
}
Program
with
annotations Error Error
Annotation
Checker
Plugins
Annotation Types
• Marker
• Single-Element
• Full-value or multi-value
Marker
• Marker annotations take no parameters. They
are used to mark a Java element to be
processed in a particular way.
• Example:
public @interface MyAnnotation {
}
• Usage:
@MyAnnotation
public void mymethod() {
....
}
Single-Element
• Single-element, or single-value type, annotations
provide a single piece of data only. This can be
represented with a data=value pair or, simply with the
value (a shortcut syntax) only, within parenthesis.
• Example:
public @interface MyAnnotation {
String doSomething();
}
• Usage:
@MyAnnotation ("What to do")
public void mymethod() {
....
}
Full-value or multi-value
• Full-value type annotations have multiple data members.
• Example:
public @interface MyAnnotation {
String doSomething();
int count;
String date();
}
• Usage:
@MyAnnotation (doSomething=
"What to do",
count=1,
date="09-09-2005")
public void mymethod() {
....
}
The Built-In Annotations
• Java defines seven built-in annotations.
• Four are imported from java.lang.annotation
• @Retention,
• @Documented,
• @Target,
• and @Inherited.
• Three are included in java.lang.
@Override,
@Deprecated,
and @SuppressWarnings.
The Target annotation
• @Target(ElementType.TYPE)
can be applied to any element of a class
• @Target(ElementType.FIELD)
can be applied to a field or property
• @Target(ElementType.METHOD)
can be applied to a method level annotation
• @Target(ElementType.PARAMETER)
can be applied to the parameters of a method
• @Target(ElementType.CONSTRUCTOR)
can be applied to constructors
• @Target(ElementType.LOCAL_VARIABLE)
can be applied to local variables
• @Target(ElementType.ANNOTATION_TYPE)
indicates that the declared type itself is a
Reflection
• When we have some Annotations defined in the
source code and have a mechanism through
which we can say that to what extent the
Annotations should be retained. The three
possible ways of telling this are,
Retain the Annotation in the Source Code only
Retain the Annotation in the Class file also.
Retain the Annotation Definition during the Run-
time so that JVM can make use of it.
• The Annotation that is used to achieve this is
@Retention and it takes a possible values of
SOURCE, CLASS and RUNTIME defined in
RetentionPolicy Enumeration.
Need of Annotation
• Less coding
• Easier to change
• Smarter development.
• Providing information to the Compiler.
• Providing information to the tools.
• Providing information to the Runtime System