2. 2
Object-Oriented Programming Concepts
What is an Object?
What is a Class?
What is a Message?
Encapsulation?
Inheritance?
Polymorphism/Dynamic Binding?
Data Hiding?
Data Abstraction?
www.SunilOS.com
3. 3
Java Primitive Data Types
Primitive Data Types:
o boolean true or false
o char unicode (16 bits)
o byte signed 8 bit integer
o short signed 16 bit integer
o int signed 32 bit integer
o long signed 64 bit integer
o float,double floating point values
www.SunilOS.com
4. 4
Other Data Types
Reference types (composite)
o objects
o arrays
strings are supported by a built-in class named
String (java.lang.String).
string literals are supported by the language (as a
special case).
www.SunilOS.com
6. www.SunilOS.com 6
Custom Data Type
public class Shape {
private String color = null;
private int borderWidth = 0;
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int bw) {
borderWidth = bw;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
:Shape
-color :String
-borderWidth:int
+getColor():String
+setColor()
+getBorderWidth():int
+setBorderWidth()
Members
Member
variables
Member
methods
8. www.SunilOS.com 8
Define attribute/variable
public class TestShape {
o public static void main(String[] args){
Shape s; //Declaration
s = new Shape(); //Instantiation
s.setColor(“Red”);
s.setBorderWidth(3);
….
int borderW =s.getBorderWidth();
System.out.println(borderW) ;
o }
}
S is an object here
S is an instance
here
9. Real World Entities – More Classes
www.SunilOS.com 9
:Automobile
-color :String
-speed:int
-make:String
+$NO_OF_GEARS
+getColor():String
+setColor()
+getMake():String
+setMake()
+break()
+changeGear()
+accelerator()
+getSpeed():int
:Person
-name:String
-dob : Date
-address:String
+$AVG_AGE
+getName():String
+setName()
+getAdress():String
+setAddress()
+getDob (): Date
+setDob ()
+getAge() : int
:Account
-number:String
-accountType : String
-balance:double
+getNumber():String
+setNumber()
+getAccountType():String
+setAccountType()
+deposit ()
+withdrawal ()
+getBalance():double
+fundTransfer()
+payBill()
10. www.SunilOS.com 10
Define A Class - Shape
public class Shape {
private String color = null;
private int borderWidth = 0;
public static final float PI = 3.14f;
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int bw) {
borderWidth = bw;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
:Shape
-color :String
-borderWidth:int
+$PI=3.14
+getColor():String
+setColor()
+getBorderWidth():int
+setBorderWidth()
Shape s1 = new Shape();
Shape s2 = new Shape();
S.o.p( s1.PI );
S.o.p( s2.PI );
S.o.p( Shape.PI );
11. www.SunilOS.com 11
Constructor
public class Shape {
private String color = null;
private int borderWidth = 0;
public Shape(){
System.out.println(
“This is default constructor”);
}
……………
Shape s = new Shape();
Constructor is just like a method.
It does not have return type.
Its name is same as Class name.
It is called at the time of object
instantiation (new Shape()).
Constructors are used to initialize
instance/class variables.
A class may have multiple
constructors with different number
of parameters.
12. www.SunilOS.com 12
Multiple Constructors
One class may have more than one constructors.
Multiple constructors are used to initialize different sets
of class attributes.
When a class has more than one constructors, it is called
Constructor Overloading.
Constructors those receive parameters are called
Parameterized Constructors.
13. www.SunilOS.com 13
Constructors Overloading
public class Shape {
private String color = null;
private int borderWidth = 0;
public Shape(){
System.out.println(“This is default
constuctor”)
}
public Shape (String c, int w){
color=c;
borderWidth=w;
}
Shape s = new
Shape()
s.setColor(“Red”);
s.setBorderWidth(5);
Or
Shape s = new
Shape(“Red”,5)
14. Default Constructor
Default constructor does not receive any parameter.
o public Shape(){ .. }
If User does not define any constructor then Default Constructor
will be created by Java Compiler.
But if user defines single or multiple constructors then default
constructor will not be generated by Java Compiler.
www.SunilOS.com 14
15. www.SunilOS.com 15
Declare an Instance/Object
Declare Primitive Type
int i;
i=5;
Declare Object
Shape s1,s2;
s1 = new Shape();
s2 = new Shape();
5
4 Bytes
s1
2 Bytes
s2
2 Bytes
getColor()
setColor()
getBorderWidth()
setBorderWidth()
Color
borderWidth
Color
borderWidth
16. www.SunilOS.com 16
Instance vs static attributes
instance
static
instance
static
Attributes Methods
+getColor()
+setColor()
+getBorderWidth()
+setBorderWiidth()
PI = 3.14
Shape s1, s2
s1 = new Shape()
s2 = new Shape()
color = Red
borderWidth= 5
color = White
borderWidth= 10
s1
s2
s1.getColor()
s2.getBorderWidth()
s1.PI
Shape.PI
Class
1011
1010
1010
1011
2B
2B
:Shape
-color :String
-borderWidth:int
+$PI =3.14
+getColor():String
+setColor()
+getBorderWidth():int
+setBorderWidth()
17. OOP Key Concepts
Encapsulation:
o Creates Expert Classes.
Inheritance:
o Creates Specialized Classes.
Polymorphism:
o Provides Dynamic behaviour at Runtime.
www.SunilOS.com 17
19. Expert Class
Encapsulation will create Expert class
Expert class has related attributes and method
www.SunilOS.com 19
Doctor Advocate Engineer Astronaut
21. www.SunilOS.com 21
Encapsulation
Gathering all related methods and attributes in a Class
is called encapsulation.
Often, for practical reasons, an object may wish to
expose some of its variables or hide some of its
methods.
Access Levels:
Modifier Class Subclass Package World
private X
protected X X X
public X X X X
26. www.SunilOS.com 26
How Objects are Created
Circle c = new Circle( );
Execution Time
c
Shape
Circle
Object
1.
c
Shape
Circle
Object
2.
Object
c
3.
Shape
Circle
27. www.SunilOS.com 27
Parents Can Keep Child’s Reference
Circle c = new Circle();
o c.getColor()
o c.getBorderBidth()
o c.area()
Shape s = new Circle();
o s.getColor()
o s.getBorderBidth()
o s.area()
Circle c1 = (Circle) s;
o c1.getColor()
o c1.getBorderBidth()
o c1.area()
28. www.SunilOS.com 28
Parents Can Keep Child’s Reference
Shape s = new Circle( );
Execution Time
s
Shape
Circle
Object
1.
s
Shape
Circle
Object
2.
Object
s
3.
Shape
Circle
Accessible
Window
31. Final Class: does not have child
www.SunilOS.com 31
The Complete Man
Does not need specialization
32. Final class: the complete class
Final class does not have child. It is defined by
final keyword
public final class String {.. }
www.SunilOS.com
32
:String
+length()
+toUpperCase()
+toLowerCase()
+indexOf()
+replace()
+substring()
:Math
+max()
+min()
+sqrt ()
+abs()
+random()
+sin()
+tan()
33. www.SunilOS.com 33
The Final modifier
Class :
o Final classes can not have Children.
o public final class Math
Method:
o Final Methods can not be overridden.
o public final double sqrt(int i);
Attribute:
o Final attributes can be assigned a value once in a life.
o public final float PI = 3.14;
35. www.SunilOS.com 35
Polymorphism
Three Common Uses of Polymorphism:
o Using Polymorphism in Arrays.
o Using Polymorphism for Method Arguments.
o Using Polymorphism for Method Return Type.
Ways to Provide polymorphism:
o Through Interfaces.
o Method Overriding.
o Method Overloading.
36. www.SunilOS.com 36
1) Using Polymorphism in Arrays
Shape s[] = new Shape[3];
s[0] = new Rectangle()
s[1] = new Circle()
s[2] = new Triangle()
s[0]:Rectangle
color
borderWidth
length = 17
Width = 35
s[1]:Circle
color
borderWidth
radius = 11
s[2]:Triangle
color
borderWidth
base:15
hight:7
37. www.SunilOS.com 37
1) Using Polymorphism in Arrays
Shape[] s;
s = new Shape[3];
s[0] = new Rectangle()
s[1] = new Circle()
s[2] = new Triangle()
2B
3
[0]
[1]
[2]
length
color
borderWidth
length
width
color
borderWidth
radius
color
borderWidth
Base
hight
1010
1111
1011
1010
1011
1111
1000
1000
38. www.SunilOS.com 38
2) Using Polymorphism for Method Arguments
public static void main(String[] args) {
Shape[] s = new Shape[3];
s[0] = new Rectangle();
s[1] = new Circle();
s[2] = new Triangle();
double totalArea = calcArea(s);
System.out.println(totalArea);
}
public static double calcArea(Shape[] s) {
double totalArea = 0;
for(int i =0;i<s.length; i++){
totalArea += s[i].area();
}
return totalArea;
}
*The method overriding is an example of runtime polymorphism.
39. www.SunilOS.com 39
3) Polymorphism using Return Type
public static Shape getShape(int i) {
if (i == 1) return new Rectangle();
if (i == 2) return new Circle();
if (i == 3) return new Triangle();
}
42. www.SunilOS.com 42
Abstract Class
What code can be written in Shape.area() method?
o Nothing, area() method is defined by child classes. It should have only
declaration.
Is Shape a concrete class?
o NO, Rectangle, Circle and Triangle are concrete classes.
If it has only area declaration then
o Method will be abstract and class will be abstract as well.
Benefit?
o Parent will enforce child to implement area() method.
o Child has to mandatorily define (implement) area method.
o This will achieve polymorphism.
43. www.SunilOS.com 43
Shape
public abstract class Shape {
String color = null;
int borderWidth = 0;
public int getBorderWidth() {
return borderWidth;
}
…
public abstract double area();
}
Instance of an abstract class can not be created
o Shape s= new Shape();
44. www.SunilOS.com 44
Interface
When all methods are abstract then interface is created.
It has abstract methods and constants.
It represents a role (abstract view) for a class.
One interface can extend another interface using
extends keyword.
One Class can implement multiple interfaces using
implements keyword.
51. Data Abstraction ( Cont. )
Data abstraction is the way to create complex data types
and exposing only meaningful operations to interact with
data type, whereas hiding all the implementation details
from outside world.
Data Abstraction is a process of hiding the
implementation details and showing only the
functionality.
Data Abstraction in java is achieved by interfaces and
abstract classes.
www.SunilOS.com 51
53. Data Hiding ( Cont. )
Data Hiding is an aspect of Object Oriented
Programming (OOP) that allows developers to
protect private data and hide implementation
details.
Developers can hide class members from other
classes. Access of class members can be
restricted or hide with the help of access
modifiers.
www.SunilOS.com 53
54. www.SunilOS.com 54
How a constructor can call another constructor ?
public class Person {
protected String firstName = null;
protected String lastName = null;
protected String address = null;
public Person() {
System.out.println("Person Default Con");
}
public Person(String fn, String ln) {
o firstName = fn;
o lastName = ln;
o System.out.println(“2 params constructor is called");
}
55. www.SunilOS.com 55
How a constructor can call another constructor ?
public Person(String fn, String ln, String address) {
o firstName = fn;
o lastName = ln;
o this.address = address;
o System.out.println(“3 params constructor is called");
}
56. www.SunilOS.com 56
How a constructor can call another constructor ?
public Person() {
System.out.println("Person Default Con");
}
public Person(String fn, String ln) {
o firstName = fn;
o lastName = ln;
o System.out.println("2 params constructor is called");
}
public Person(String fn, String ln, String address) {
1. this(fn,ln) ;
2. this.address = address;
3. System.out.println(“3 params constructor is called");
}
57. www.SunilOS.com 57
How to Call Parent Constructor
public class Employee extends Person {
private String designation = null;
public Employee() {
System.out.println("Default Constructor");
}
public Employee(String fn, String ln, String des) {
super(fn, ln);
designation = des;
System.out.println(“3 params constructor is called");
}
58. www.SunilOS.com 58
Super default constructor
If Child constructor does not call parent’s constructor then Parent’s default
constructor is automatically called.
public Employee() {
System.out.println("Default Constructor");
}
Is Equal to
public Employee() {
super();
System.out.println("Default Constructor");
}
59. www.SunilOS.com 59
Super default constructor (cont.)
public Employee(String fn, String ln, String des) {
o designation = des;
o System.out.println(“3 params constructor is called ");
}
Is Equal to
public Employee(String fn, String ln, String des) {
o super();
o designation = des;
o System.out.println(“3 params constructor is called");
}
60. www.SunilOS.com 60
How to call Parent’s overridden method?
public class Person {
public void changeAddress() {
o System.out.println("Person change Address");
}
…
public class Employee extends Person {
public void changeAddress() {
o System.out.println("*****");
o super.changeAddress();
o System.out.println("Employee change Address");
}
…
61. www.SunilOS.com 61
Interesting facts - Overriding
public class Account{
o public int getAmount() {
o return 5;
o }
}
public class SavingAccount extends Account {
o public int getAmount() {
return 10;
o }
}
62. www.SunilOS.com 62
What is Output Of
public class Test {
public static void main(String[] args) {
o SavingAccount s = new SavingAccount ();
o Account a = new Account ();
o Account sa = new SavingAccount ();
o System.out.println(s.getAmount());
o System.out.println(a.getAmount());
o System.out.println(sa.getAmount());
o }
}
63. Interesting facts - Overriding
public class Account{
o public int getAmount() {
o return 5;
o }
}
public class SavingAccount extends Account{
o public int getAmount() {
int i = super.getAmount() + 10;
return i;
o }
}
www.SunilOS.com 63
64. www.SunilOS.com 64
Constructor and Inheritance
class A {
...
}
class B extends A {
public B(int x){}
}
B b = new B(3);
OK
-default constr. A()
-B(int x)
Implicit call of base class constructor
class A {
public A() {...}
}
class B extends A {
public B(int x) {...}
}
B b = new B(3);
OK
-A()
-B(int x)
class A {
public A(int x) {...}
}
class B extends A {
public B(int x) {...}
}
B b = new B(3);
Error!
-no explicit call of
the A() constructor
-default constr. A()
does not exist
class A {
public A(int x) {...}
}
class B extends A {
public B(int x){
super(x) ...}
}
B b = new B(3);
OK
-A(int x)
-B(int x)
Explicit call
68. Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 68