1. Abstraction
– Representing the essential feature with including background details or
Explanation.
Encapsulation
– Binding data and methods into single unit.
Inheritance
– Object of one class acquire the properties of object of another class.
Polymorphism
Ability to take more than one form.
Dynamic binding
Code associated with given procedure call is not known until the time of call at
runtime.
02/23/18
Implementing the Object Oriented Programming.
2. History of Java
Java is a general purpose object oriented programming
language.
Developed by Sun Microsystems. (James Gostling) in 1991.
Initially called “Oak” but was renamed as “Java” in 1995.
Initial motivation is to develop a platform independent
language to create software to be embedded in various
consumer electronics devices.
Become the language of internet. (portability and security).
02/23/18
2
3. Features of Java
1. Compiled and Interpreted
2. Object Oriented
3. Platform Independent and portable
4. Robust and Secure
5. Distributed / Network Oriented
6. Multithreaded and Interactive
7. High Performance
8. Dynamic
9. Simple, Small and Familiar
02/23/18
3
4. Java Virtual Machine
Java compiler produces an intermediate code known as
byte code for a machine, known as JVM.
It exists only inside the computer memory.
Machine code is generated by the java interpreter by acting
as an intermediary between the virtual machine and real
machine.
02/23/18
Java Program Java Compiler Bytecode(virtual machine)
Bytecode Java Interpreter Machine Code
4
Mosarratj Jahan, Dept. of CSE,
5. Compiled and Interpreted
Java works in two stage
Java compiler :translate the source code into byte code.
Java interpreter converts the byte code into machine
level representation.
Byte Code:
-A highly optimized set of instructions to be executed by
the java runtime system, known as java virtual machine
(JVM).
-Not executable code.
Java Virtual Machine (JVM):
- Need to be implemented for each platform.
- Although the details vary from machine to machine, all
JVM understand the same byte code.
02/23/18
5
6. Object Oriented
Fundamentally based on OOP
Classes and Objects
Efficient re-use of packages such that the
programmer only cares about the interface and not
the implementation
The object model in java is simple and easy to
extend.
02/23/18
6
Mosarratj Jahan, Dept. of CSE, DU
7. Platform Independent and
Portable
“Write-Once Run-Anywhere”
A Java program written and compiled on one machine can be
executed on any other machine
Changes in system resources will not force any change in the
program.
The Java Virtual Machine (JVM) Convert byte code into
machine level representation.
02/23/18
7
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
8. Total Platform Independence
02/23/18
JAVA COMPILERJAVA COMPILER
JAVA BYTE CODEJAVA BYTE CODE
JAVA INTERPRETERJAVA INTERPRETER
Windows 95 Macintosh Solaris Windows NT
(translator)
(same for all platforms)
(one for each different system)
9. Robust and Secure
Checks the reliability of the code before Execution
interms of
Strict compile time and run time checking of data type.
Exception handling
It verify all memory access
Ensure that no viruses are communicated with an
applet.
Garbage-collected language.
Security-:
First Check the Code either it is Effected by the Virus .
Absence of pointer concept
02/23/18
9
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
10. Distributed and Network Oriented
• Java grew up in the days of the Internet
– Inherently network friendly
– Original release of Java came with Networking
libraries
– Newer releases contain even more for handling
distributed applications
• RMI, Transactions
02/23/18
10
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
11. Multithreaded and Interactive
Handles multiple tasks simultaneously.
Java runtime system contains tools to support multiprocess
synchronization and construct smoothly running interactive
systems.
02/23/18
11
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
12. High Performance
Java performance is slower than C
Provisions are added to reduce overhead at runtime.
Incorporation of multithreading enhance the overall
execution speed.
Just-in-Time (JIT) can compile the byte code into
machine code.
• Can sometimes be even faster than compiled C code!
02/23/18
12
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
13. Dynamic
Capable of dynamically linking a new class libraries,
methods and objects.
Java can use efficient functions available in C/C++.
Installing new version of library automatically updates all
programs
02/23/18
13
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
14. Simple, Small and Familiar
Similar to C/C++ in syntax
But eliminates several complexities of
No operator overloading
No direct pointer manipulation or pointer
arithmetic
No multiple inheritance
No malloc() and free() – handles memory
automatically
02/23/18
14
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
15. Versions of Java
Three versions of the Java 2 Platform, targeted at different uses
Java 2 Micro Edition (J2ME)
Very small Java environment for smart cards,phones, and set-top boxes
Java 2 Standard Edition (J2SE)
The basic platform
J2SE can be used to develop client-side standalone applications or applets.
Java 2 Enterprise Edition (J2EE)
For business applications, web services, mission-critical systems.
Transaction processing, databases, distribution, replication.
02/23/18
15
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
16. Java Program Structure
Documentation section
Package Statement
Import statements
Interface Statements
Class Definitions
Main method class
{
Main method definition
}
02/23/18
Suggested
Optional
Optional
Optional
Optional
Essential
17. Classes
• A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.
17
Class Circle
radius
circumference()
area()
18. Class Declaration
class <classname>
{
type instance_varible1;
type instance_varible2;
..
..
type methodname1(parameter list)
{
//body of method
}
type methodname2(parameter ist)
{
//body of method
}
}
02/23/18
19. Adding Methods
• Methods are declared inside the body of the class
but immediately after the declaration of data fields.
• The general form of a method declaration is:
19
return type MethodName (parameter-list)
{
Method-body;
}
20. Hello Internet
// hello.java: Hello Internet program
class hello
{
public static void main(String args[])
{
System.out.println(“Hello
Internet”);
}
}
21. Adding fields and Methods to Class Circle
21
public class Circle {
public double r=10; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
22. 02/23/18
public class TestCircles
{
public static void main(String args[])
{
Circle circleC = new Circle();
double circum=circleC. circumference() ;
System.out.println(“circumference”+circum);
double ar=circleC. area();
System.out.println(“Area”+area);
}
}
23. Creating objects of a class
• Objects are created dynamically using the new keyword.
For ex.
Circle cir; //declare varible;
cir=new Circle(); //instantiate the object
Circle cir=new Circle(); //Both statement combined
nullcir
Circle Objectcir
24. Assigning one object reference variable to another
Circle cir1=new Circle();
Circle cir2=cir1;
Circle Object
cir1
cir2
25. What is a Constructor?
• Constructor is a special method that gets invoked
“automatically” at the time of object creation.
• Constructor is normally used for initializing objects
with default values unless different values are
supplied.
• Constructor has the same name as the class name.
• Constructor cannot return values.
• A class can have more than one constructor as long
as they have different signature (i.e., different input
arguments syntax).
02/23/18
26. Defining a Constructorpublic class ClassName
{
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
27. Defining a Constructor: Example
public class Counter {
int CounterIndex;
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
28. class MyClass
{
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
System.out.println(“CounterIndex=:”+a);
counter1.decrease ();
int b = counter1.getCounterIndex();
System.out.println(“CounterIndex=:”+b);
}
}
29. Defining a multiple Constructor: Example
public class Counter {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
30. Multiple Constructors
30
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
31. 31
Initializing with constructors
public class TestCircles {
public static void main(String args[]){
Circle circleA = new Circle( 10.0, 12.0, 20.0);
Circle circleB = new Circle(10.0);
Circle circleC = new Circle();
}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(10)
(x,y) = (0,0)
Radius=10
circleC = new Circle()
(x,y) = (0,0)
Radius = 1
(x.y) = (10,12)
Radius = 20
32. 32
Method Overloading
• Constructors all have the same name.
• Methods are distinguished by their signature:
– name
– number of arguments
– type of arguments
• That means, a class can also have multiple usual
methods with the same name. - polymorphism.
• The method body can have different logic depending
on the data type of arguments
33. Method Overloading:Example
class Overload {
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + "," + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading {
public static void main(String args[]) {
Overload overload = new Overload();
double result;
overload.test(10);
overload.test(10, 20);
result = overload.test(5.5);
System.out.println("Result : " + result);
}
}
02/23/18
34. 34
Static Members
• Java supports definition of global methods and variables that
can be accessed without creating objects of a class. Such
members are called Static members.
• Define a variable by marking with the static methods.
• This feature is useful when we want to create a variable
common to all objects of a class.
• One of the most common example is to have a variable that
could keep a count of how many objects of a class have been
created.
• Note: Java creates only one copy for a static variable which
can be used even if the class is never instantiated.
35. 35
Static Variables
• Define using static:
• Access with the class name (ClassName.StatVarName):
public class Circle {
// class variable, one for the Circle class, how many circles
public static int numCircles;
//instance variables,one for each instance of a Circle
public double x,y,r;
// Constructors...
}
nCircles = Circle.numCircles;
36. 36
Static Variables - Example
• Using static variables:
public class Circle {
// class variable, one for the Circle class, how many circles
private static int numCircles = 0;
private double x,y,r;
// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}
37. 37
Class Variables - Example
• Using static variables:
public class CountCircles {
public static void main(String args[]){
Circle circleA = new Circle( 10, 12, 20); // numCircles = 1
Circle circleB = new Circle( 5, 3, 10); // numCircles = 2
}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10)
numCircles=2
38. 38
Instance Vs Static Variables
• Instance variables : One copy per object.
Every object has its own instance variable.
– E.g. x, y, r (centre and radius in the circle)
• Static variables : One copy per class.
– E.g. numCircles (total number of circle objects
created)
39. 39
Static Methods
• A class can have methods that are defined as static
(e.g., main method).
• Static methods can be accessed without using
objects. Also, there is NO need to create objects.
• They are prefixed with keyword “static”
• Static methods are generally used to group related
library functions that don’t depend on data members
of its class. For example, Math library functions.
40. 40
Comparator class with Static methods// Comparator.java: A class with static data items comparision methods
class Comparator {
public static int max(int a, int b)
{
if( a > b)
return a;
else
return b;
}
public static String max(String a, String b)
{
if( a.compareTo (b) > 0)
return a;
else
return b;
}
}
class MyClass {
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";
int a = 10;
int b = 20;
System.out.println(Comparator.max(a, b)); // which number is big
System.out.println(Comparator.max(s1, s2)); // which city is big
System.out.println(Comparator.max(s1, s3)); // which city is big
}
}
Directly accessed using ClassName (NO Objects)
41. 41
Static methods restrictions
• They can only call other static methods.
• They can only access static data.
• They cannot refer to “this” or “super” (more
later) in anyway.
42. Program compilation and execution
• Compilation
# javac hello.java
results in hello.class
• Execution
# java hello
Hello Internet
#
43. INHERITANCE BASICS
1. Reusability is achieved by INHERITANCE
2. Java classes Can be Reused by extending a class. Extending
an existing class is nothing but reusing properties of the
existing classes.
3. The class whose properties are extended is known as super
or base or parent class.
4. The class which extends the properties of super class is
known as sub or derived or child class
5. A class can either extends another class or can implement an
interface
44. A
B
class B extends A { ….. }
A super class
B sub class
A
B
<<class>>
<<class>>
<<class>>
<<interface>>class B implements A { ….. }
A interface
B sub class
45. Various Forms of Inheritance
A
B
Single Inheritance
A
B
Hierarchical Inheritance
X
A B C
X
A B C
MultiLevel Inheritance
A
B
C
A
B
C
A B
C
Multiple Inheritance
NOT SUPPORTED BY JAVA
A B
C
SUPPORTED BY JAVA
46. Forms of Inheritance
• Mulitiple Inheritance can be implemented by
implementing multiple interfaces not by extending
multiple classes
Example :
class Z extends A implements C , D
{ …………}
OK
class Z extends A ,B class Z extends A extends B
{ {
OR
} }
A C D
Z
WRONG WRONG
47. Defining a Subclass
Syntax :
class <subclass name> extends <superclass name>
{
variable declarations;
method declarations;
}
• Extends keyword signifies that properties of the super
class are extended to sub class
• Sub class will not inherit private members of super class
48. Access Control
Access Modifiers
Access Location
public protected friendly private
Same Class Yes Yes Yes Yes
sub classes in same
package
Yes Yes Yes No
Other Classes in
Same package
Yes Yes Yes No
Subclasses in other
packages
Yes Yes No No
Non-subclasses in
other packages
Yes No No No
49. 1. Whenever a sub class object is created ,super class
constructor is called first.
2. If super class constructor does not have any
constructor of its own OR has an unparametrized
constructor then it is automatically called by Java Run
Time by using call super()
3. If a super class has a parameterized constructor then it
is the responsibility of the sub class constructor to call
the super class constructor by call
super(<parameters required by super class>)
4. Call to super class constructor must be the first
statement in sub class constructor
Inheritance Basics
50. Inheritance Basics
When super class has a Unparametrized constructor
class A
{
A()
{
System.out.println("This is constructor of class A");
}
} // End of class A
class B extends A
{
B()
{
super();
System.out.println("This is constructor of class B");
}
} // End of class B
Optional
Cont…..
51. class inhtest
{
public static void main(String args[])
{
B b1 = new B();
}
}
OUTPUT
This is constructor of class A
This is constructor of class B
52. class A
{
private int a;
A( int a)
{
this.a =a;
System.out.println("This is
constructor of class A");
} }
class B extends A
{
private int b;
private double c;
B(int a,int b,double c)
{
super(a);
this.b=b;
this.c=c;
System.out.println("This is
constructor of class B");
} }
B b1 = new B(8,10,8.6);
OUTPUT
This is constructor of class A
This is constructor of class B
53. public class Superclass
{
public void printMethod()
{
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass
{ // overrides printMethod in Superclass
public void printMethod()
{
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{
Subclass s = new Subclass();
s.printMethod();
}
}
02/23/18
54. USE OF super KEYWORD
• Can be used to call super class constrctor
super();
super(<parameter-list>);
• Can refer to super class instance
variables/Methods
super.<super class instance variable/Method>
55. class A
{
private int a;
A( int a)
{
this.a =a;
System.out.println("This is constructor
of class A");
}
void show()
{
System.out.println("a="+a);
}
void display()
{
System.out.println("hello This is Display
in A");
}
}
class B extends A
{
private int b;
private double c;
B(int a,int b,double c)
{
super(a);
this.b=b;
this.c=c;
System.out.println("This is constructor
of class B");
}
void show()
{
super.show();
System.out.println("b="+b);
System.out.println("c="+c);
display();
}
}
56. class inhtest1
{
public static void main(String args[])
{
B b1 = new B(10,8,4.5);
b1.show();
}
}
/* OutPut
D:javabin>java inhtest1
This is constructor of class A
This is constructor of class B
a=10
b=8
c=4.5
hello This is Display in A
*/