SlideShare una empresa de Scribd logo
1 de 56
www.SunilOS.com 1
www.sunilos.com
www.raystec.com
Object Oriented Programming
OOP……. Not OOPS!!
Agenda
Classes and Objects
Constructors
Encapsulation
Inheritance
Polymorphism
Data Abstraction
Data Hiding
www.SunilOS.com 2
3
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
4
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
5
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
www.SunilOS.com 6
Attributes
String color = “Red” ;
int borderWidth = 5 ;
//……
System.out.println(borderWidth);
www.SunilOS.com 7
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
www.SunilOS.com 8
Method Definition
public class Shape {
..
public void setBorderWidth(int bw)
{
borderWidth = bw;
}
}
Method
www.SunilOS.com 9
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
Real World Entities – More Classes
www.SunilOS.com 10
: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()
www.SunilOS.com 11
Define A Class - Shape
public class Shape {
private string color = null;
private int borderWidth = 0;
public static final float PI = 3.14;
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 );
www.SunilOS.com 12
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.
www.SunilOS.com 13
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.
www.SunilOS.com 14
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);
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 15
www.SunilOS.com 16
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
www.SunilOS.com 17
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()
OOP Key Concepts
Encapsulation:
o Creates Expert Classes.
Inheritance:
o Creates Specialized Classes.
Polymorphism:
o Provides Dynamic behaviour at Runtime.
www.SunilOS.com 18
www.SunilOS.com 19
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
www.SunilOS.com 20
Inheritance
:Shape
color :String
borderWidth:int
getColor():String
setColor()
getBorderWidth():int
setBorderWidth()
:Rectangle
length :int
width:int
area()
getLength()
setLength()
:Circle
radius : int
area()
getRadius()
setRadius()
:Triangle
base:int
hight:int
area()
getBase()
setBase()
Circle c =new Circle();
c.getColor();
c.getBorderWidth();
c.area();
:Object
UML Notation
www.SunilOS.com 21
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
www.SunilOS.com 22
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()
www.SunilOS.com 23
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
www.SunilOS.com 24
Method Overriding – area()
:Shape
Color :String
borderWidth:int
getColor():String
setColor()
getBorderWidth():int
setBorderWidth()
area()
:Rectangle
length :int
width:int
area()
getLength()
setLength()
:Circle
radius
area()
getRadius()
setRadius()
:Triangle
base:int
hight:int
area()
getBase()
setBase()
Shape s = new Circle();
s.getColor();
s.getBorderWidth();
s.area();
www.SunilOS.com 25
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.
www.SunilOS.com 26
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
www.SunilOS.com 27
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
www.SunilOS.com 28
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.
www.SunilOS.com 29
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();
}
www.SunilOS.com 30
Method Overloading
PrintWriter
o println(String)
o println(int)
o println(double)
o println(boolean)
o println()
www.SunilOS.com 31
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;
www.SunilOS.com 32
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.
www.SunilOS.com 33
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();
www.SunilOS.com 34
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.
www.SunilOS.com 35
Interfaces
Richman
earnMony()
donation()
party()
Businessman
name
address
earnMony()
donation()
party()
Richman rm = new Businessman();
SocialWorker sw = new Businessman();
Businessman bm = new Businessman();
SocialWorker
helpToOthers()
Businessman
name
address
earnMony()
donation()
party()
helpToOthers()
Businessman
name
address
helpToOthers()
www.SunilOS.com 36
interface Richman
public interface Richman {
o public void earnMoney();
o public void donation();
o public void party();
}
www.SunilOS.com 37
interface SocialWorker
public interface SocialWorker{
o public void helpToOthers();
}
www.SunilOS.com 38
interface SocialWorker
 public class Businessman extends Person
implements Richman, SocialWorker {
 private String name;
 private String address;
 public void donation() {
o System.out.println("Giving Donation");
 }
www.SunilOS.com 39
Interface
It declares APIs.
Specifications are defined as interfaces.
o JDBC
o Collection
o EJB
o JNI
o etc.
Data Abstraction
www.SunilOS.com 40
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 41
Data Hiding
www.SunilOS.com 42
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 43
www.SunilOS.com 44
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");
 }
www.SunilOS.com 45
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");
 }
www.SunilOS.com 46
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");
 }
www.SunilOS.com 47
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");
 }
www.SunilOS.com 48
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");
 }
www.SunilOS.com 49
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");
 }
www.SunilOS.com 50
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");
 }
 …
www.SunilOS.com 51
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 }
 }
www.SunilOS.com 52
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 }
 }
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 53
www.SunilOS.com 54
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
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 55
Thank You!
www.SunilOS.com 56
www.SunilOS.com

Más contenido relacionado

La actualidad más candente

Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheetanand_study
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 

La actualidad más candente (19)

Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 

Similar a OOP v3

C# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusC# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusRaimundas Banevičius
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsMohammad Shaker
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfVishalKumarJha10
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesAbhishek Sur
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212Mahmoud Samir Fayed
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languagesArthur Xavier
 
Please help me make a UML for Java! Look at the code below and make a.docx
Please help me make a UML for Java! Look at the code below and make a.docxPlease help me make a UML for Java! Look at the code below and make a.docx
Please help me make a UML for Java! Look at the code below and make a.docxJakeT2gGrayp
 

Similar a OOP v3 (20)

OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
C# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusC# v8 new features - raimundas banevicius
C# v8 new features - raimundas banevicius
 
L10
L10L10
L10
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
JavaTalks: OOD principles
JavaTalks: OOD principlesJavaTalks: OOD principles
JavaTalks: OOD principles
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Please help me make a UML for Java! Look at the code below and make a.docx
Please help me make a UML for Java! Look at the code below and make a.docxPlease help me make a UML for Java! Look at the code below and make a.docx
Please help me make a UML for Java! Look at the code below and make a.docx
 
Parameters
ParametersParameters
Parameters
 
Chapter04.pptx
Chapter04.pptxChapter04.pptx
Chapter04.pptx
 
Objects and Graphics
Objects and GraphicsObjects and Graphics
Objects and Graphics
 

Más de Sunil OS

Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 

Más de Sunil OS (20)

Threads V4
Threads  V4Threads  V4
Threads V4
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
DJango
DJangoDJango
DJango
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
Hibernate
Hibernate Hibernate
Hibernate
 
C++ oop
C++ oopC++ oop
C++ oop
 
C Basics
C BasicsC Basics
C Basics
 
Log4 J
Log4 JLog4 J
Log4 J
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 

Último

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Último (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

OOP v3

  • 3. 3 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
  • 4. 4 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
  • 5. 5 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 Attributes String color = “Red” ; int borderWidth = 5 ; //…… System.out.println(borderWidth);
  • 7. www.SunilOS.com 7 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 Method Definition public class Shape { .. public void setBorderWidth(int bw) { borderWidth = bw; } } Method
  • 9. www.SunilOS.com 9 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
  • 10. Real World Entities – More Classes www.SunilOS.com 10 :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()
  • 11. www.SunilOS.com 11 Define A Class - Shape public class Shape { private string color = null; private int borderWidth = 0; public static final float PI = 3.14; 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 );
  • 12. www.SunilOS.com 12 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.
  • 13. www.SunilOS.com 13 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.
  • 14. www.SunilOS.com 14 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);
  • 15. 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 15
  • 16. www.SunilOS.com 16 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
  • 17. www.SunilOS.com 17 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()
  • 18. OOP Key Concepts Encapsulation: o Creates Expert Classes. Inheritance: o Creates Specialized Classes. Polymorphism: o Provides Dynamic behaviour at Runtime. www.SunilOS.com 18
  • 19. www.SunilOS.com 19 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
  • 20. www.SunilOS.com 20 Inheritance :Shape color :String borderWidth:int getColor():String setColor() getBorderWidth():int setBorderWidth() :Rectangle length :int width:int area() getLength() setLength() :Circle radius : int area() getRadius() setRadius() :Triangle base:int hight:int area() getBase() setBase() Circle c =new Circle(); c.getColor(); c.getBorderWidth(); c.area(); :Object UML Notation
  • 21. www.SunilOS.com 21 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
  • 22. www.SunilOS.com 22 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()
  • 23. www.SunilOS.com 23 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
  • 24. www.SunilOS.com 24 Method Overriding – area() :Shape Color :String borderWidth:int getColor():String setColor() getBorderWidth():int setBorderWidth() area() :Rectangle length :int width:int area() getLength() setLength() :Circle radius area() getRadius() setRadius() :Triangle base:int hight:int area() getBase() setBase() Shape s = new Circle(); s.getColor(); s.getBorderWidth(); s.area();
  • 25. www.SunilOS.com 25 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.
  • 26. www.SunilOS.com 26 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
  • 27. www.SunilOS.com 27 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
  • 28. www.SunilOS.com 28 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.
  • 29. www.SunilOS.com 29 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(); }
  • 30. www.SunilOS.com 30 Method Overloading PrintWriter o println(String) o println(int) o println(double) o println(boolean) o println()
  • 31. www.SunilOS.com 31 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;
  • 32. www.SunilOS.com 32 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.
  • 33. www.SunilOS.com 33 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();
  • 34. www.SunilOS.com 34 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.
  • 35. www.SunilOS.com 35 Interfaces Richman earnMony() donation() party() Businessman name address earnMony() donation() party() Richman rm = new Businessman(); SocialWorker sw = new Businessman(); Businessman bm = new Businessman(); SocialWorker helpToOthers() Businessman name address earnMony() donation() party() helpToOthers() Businessman name address helpToOthers()
  • 36. www.SunilOS.com 36 interface Richman public interface Richman { o public void earnMoney(); o public void donation(); o public void party(); }
  • 37. www.SunilOS.com 37 interface SocialWorker public interface SocialWorker{ o public void helpToOthers(); }
  • 38. www.SunilOS.com 38 interface SocialWorker  public class Businessman extends Person implements Richman, SocialWorker {  private String name;  private String address;  public void donation() { o System.out.println("Giving Donation");  }
  • 39. www.SunilOS.com 39 Interface It declares APIs. Specifications are defined as interfaces. o JDBC o Collection o EJB o JNI o etc.
  • 41. 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 41
  • 43. 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 43
  • 44. www.SunilOS.com 44 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");  }
  • 45. www.SunilOS.com 45 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");  }
  • 46. www.SunilOS.com 46 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");  }
  • 47. www.SunilOS.com 47 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");  }
  • 48. www.SunilOS.com 48 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");  }
  • 49. www.SunilOS.com 49 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");  }
  • 50. www.SunilOS.com 50 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");  }  …
  • 51. www.SunilOS.com 51 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 }  }
  • 52. www.SunilOS.com 52 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 }  }
  • 53. 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 53
  • 54. www.SunilOS.com 54 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
  • 55. 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 55

Notas del editor

  1. www.sunilos.com
  2. www.sunrays.co.in
  3. www.sunrays.co.in
  4. www.sunrays.co.in
  5. www.sunrays.co.in
  6. www.sunrays.co.in
  7. www.sunrays.co.in
  8. www.sunrays.co.in
  9. www.sunrays.co.in
  10. www.sunrays.co.in
  11. www.sunrays.co.in
  12. www.sunrays.co.in
  13. www.sunrays.co.in
  14. www.sunrays.co.in
  15. www.sunrays.co.in
  16. www.sunrays.co.in
  17. www.sunrays.co.in
  18. www.sunrays.co.in
  19. www.sunrays.co.in
  20. www.sunrays.co.in
  21. www.sunrays.co.in
  22. www.sunrays.co.in
  23. www.sunrays.co.in
  24. www.sunrays.co.in
  25. www.sunrays.co.in
  26. www.sunrays.co.in
  27. www.sunrays.co.in
  28. www.sunrays.co.in
  29. www.sunrays.co.in
  30. www.sunrays.co.in
  31. www.sunrays.co.in
  32. www.sunrays.co.in
  33. www.sunrays.co.in
  34. www.sunrays.co.in
  35. www.sunrays.co.in
  36. www.sunrays.co.in
  37. www.sunrays.co.in
  38. www.sunrays.co.in
  39. www.sunrays.co.in
  40. www.sunrays.co.in
  41. www.sunrays.co.in
  42. www.sunrays.co.in
  43. www.sunrays.co.in
  44. www.sunrays.co.in
  45. www.sunrays.co.in
  46. www.sunrays.co.in