Understanding Object-Oriented Programming Concepts

 
Objects and Class
 
 
Object Oriented Programming
 
1
Object Oriented Programming
Object-oriented programming enables
you to develop large-scale software and
GUIs 
effectively.
However, these Java features (whatever
learnt so far) 
are not sufficient for
developing graphical user interfaces and
large-scale software systems.
Suppose you want to develop a graphical
user interface as shown below:
Object Oriented Programming
2
 
Defining classes for objects
 
A class defines the 
properties
 and
behaviors
 for objects.
An 
object 
represents 
an entity in the real
world that can be distinctly identified.
For example, a student, a desk, a circle, a
button, and even a loan can all be viewed
as objects.
 
Object Oriented Programming
 
3
 
Cont.
 
An object has a unique 
identity, state, and
behavior.
The 
state 
of an object (also known as its 
properties 
or 
attributes
) is
represented by 
data fields 
with their current values.  A circle object, for
example, has a data field 
radius
, which is the property that
characterizes a circle. A rectangle object has the data fields 
width 
and
height
, which are the properties that characterize a rectangle.
The behavior of an object (also known as its actions) is defined by
methods
. To invoke a method on an object is to ask the object to
perform an action. For example, you may define methods named
getArea() and getPerimeter() for circle objects. A circle object may
invoke getArea() to return its area and getPerimeter() to return its
perimeter. You may also define the setRadius(radius) method. A circle
object can invoke this method to change its radius.
 
Object Oriented Programming
 
4
 
Cont.
 
A 
class 
is a 
template, blueprint, or 
contract
that defines what an object’s data fields
and methods will be.
An object is an 
instance
 of a class. You can
create many instances of a class. Creating
an instance is referred to as 
instantiation
.
A Java class uses 
variables to define data
fields
 and 
methods to define
actions/behaviour
.
 
Object Oriented Programming
 
5
 
Cont.
 
Additionally, a class provides methods of a
special type, known as 
constructors
, which
are invoked to create a new object.
A constructor 
can perform any action
,
but constructors are 
designed to perform
initializing actions
, such as initializing the
data fields of objects.
 
Object Oriented Programming
 
6
undefined
 
Object Oriented Programming
 
7
undefined
 
Object Oriented Programming
 
8
 
Another way to write the same program
SimpleCircle.java
The above class is different from all the classes we have seen so far.
The class which contains main method is called main class.
 
TestSimpleCircle.java
 
Cont.
 
You can put the more than 
one classes into
one file
, but only one class in the file 
can be
a 
public class
.
Furthermore, 
the public class must have the
same name as the file name
. Therefore, the
file name is 
TestSimpleCircle.java
, since
TestSimpleCircle 
is public. Each class in
the source code is compiled into a 
.class
file.
When you compile 
TestSimpleCircle.java
,
two class files 
TestSimpleCircle.class 
and
SimpleCircle.class 
are generated.
 
Object Oriented Programming
 
9
Cont.
In java file, 
more than one class may contain
main method
. So, we can invoke the main
method of specific class as follow:
>java a - this will call main method of class a
>java b - this will call main method of class b
Object Oriented Programming
10
Cont.
 
Consider television sets.
Each TV is an object with states (current
channel, current volume level, power on
or off) and behaviors (change channels,
adjust volume, turn on/off).
You can use a class to model TV sets.
Object Oriented Programming
11
 
TestTV.java
 
Constructor
 
A constructor is invoked to create an object
using the 
new 
operator.
Constructors are a special kind of method.
They have three peculiarities:
 A constructor must have the same name
as the class itself.
 Constructors do not have a return
type—not even 
void
.
 Constructors are invoked using the
new 
operator when an object is created.
Constructors play the role of initializing
objects.
 
Object Oriented Programming
 
12
 
Cont.
 
A class normally provides a constructor
without arguments (e.g., 
Circle()
). Such a
constructor is referred to as a 
no-arg 
or 
no-
argument constructor
.
A class may be defined without constructors.
In this case, a public no-arg constructor with
an empty body is implicitly defined in the
class. This constructor, called a 
default
constructor
, is provided automatically 
only if
no constructors are explicitly defined in the
class
.
 
Object Oriented Programming
 
13
 
Accessing object via reference
variable
 
An object’s data and methods can be
accessed through the dot (
.
) operator via
the 
object’s reference variable.
Objects are accessed via the object’s
reference variables
, which contain
references to the objects. Such variables
are declared using the following syntax:
          
ClassName objectRefVar;
 
 
Object Oriented Programming
 
14
 
Cont.
 
Accessing data field and method using dot
operator.
Reference field are set default to null.
 
Object Oriented Programming
 
15
 
Primitive type Vs Reference type
 
Every variable represents a memory
location that holds a value.
 
Object Oriented Programming
 
16
Using Classes from Java Library
The Java API contains a rich set of classes
for developing Java programs.
Date class
:
Object Oriented Programming
17
Cont.
Random class
:  Math.random()
Another way to generate random
numbers is to use the 
java.util.Random
class
Object Oriented Programming
18
 
Cont.
 
Point2D class
: Java API has a conveninent
Point2D 
class in the 
javafx.geometry
package for representing a point in a two-
dimensional plane
 
Object Oriented Programming
 
19
 
Cont.
 
Object Oriented Programming
 
20
 
Static variable, constant and
methods
 
 
 
 
The 
radius 
in 
circle1 
is independent of
the 
radius 
in 
circle2 
and is stored in a
different memory location.
Changes made to 
circle1
’s 
radius 
do not
affect 
circle2
’s 
radius
,
and vice versa.
 
Object Oriented Programming
 
21
 
Cont.
 
If you want all the instances of a class to share data,
use 
static variables
, also known as 
class variables
.
A static variable is 
shared by all objects of the same
class
. A static method 
cannot access instance
members
 of the class.
Static variables store values for the variables in a
common memory location
.
Because of this common location, if one object
changes the value of a static variable
, all objects of
the same class are affected.
Java supports static methods as well as static
variables. 
Static methods 
can be called 
without
creating an instance of the class
.
 
Object Oriented Programming
 
22
Cont.
TestCircleWithStaticMembers.java
Object Oriented Programming
23
 
Visibility modifiers
 
Visibility modifiers can be used to specify the
visibility of a class and its members.
You can use the 
public
 
visibility modifier for
classes, methods, and data fields to denote
that they can be accessed from any other
classes.
If 
no visibility modifier is used
, then by
default the classes, methods, and data fields
are accessible by any class in the same
package. This is known as 
package-private
 
or
package-access
.
 
Object Oriented Programming
 
24
 
Cont.
 
Packages can be used to organize classes
. To
do so, you need to add the following line as
the first non comment and nonblank
statement in the program:
     package 
packageName;
If a class is defined without the package
statement, it is said to be placed in the
default 
package
.
Java recommends 
that you place classes into
packages rather than using a default package.
 
Object Oriented Programming
 
25
 
Cont.
 
The 
private 
modifier makes methods
and data fields accessible only from within
its own 
class.
 
Object Oriented Programming
 
26
 
Cont.
 
If a class is not defined as public, it can be
accessed only within the same package.
 
Object Oriented Programming
 
27
 
Cont.
 
There is no restriction on accessing data
fields and methods from inside the 
class.
 
Object Oriented Programming
 
28
 
Data field encapsulation
 
Making data fields private 
protects data
and makes
 the class easy to maintain.
The data fields 
radius 
and
numberOfObjects 
in the
CircleWithStaticMembers 
class in
previous program can be modified
directly.
 
Object Oriented Programming
 
29
 
This is not a good practice—for two
reasons:
First
, data may be tampered with. For
example, 
numberOfObjects 
is to count
the number of objects created, but it may be
mistakenly set to an arbitrary value (e.g.,
CircleWithStaticMembers.numberOfObjects = 10
).
Second
, 
you want to modify the
CircleWithStaticMembers 
class to
ensure that the radius is nonnegative after
other programs have already used the class.
 
 
Cont.
 
Object Oriented Programming
 
30
Cont.
A private data field cannot be accessed by
an object from outside the class 
that
defines 
the private field.
So, how to make 
a private data field
accessible: provide a 
getter
 
method to
return its value. To enable a private data
field to be updated, provide a 
setter
method to set a new value.
A getter method is also referred to as an
accessor
 
and a setter to a 
mutator
.
Object Oriented Programming
31
TestCircleWithPrivateDataFields.java
 
Program
 
Object Oriented Programming
 
32
 
(
The Fan class) Design a class named Fan to represent a fan. The class contains:
 Three constants named 
SLOW
, 
MEDIUM
, and 
FAST
 with the values 1, 2, and 3 to denote
the fan speed.
 A private 
int
 data field named 
speed
 that specifies the speed of the fan (the default is
SLOW).
 A private 
boolean
 data field named 
on
 that specifies whether the fan is on (the default is
false).
 A private 
double
 data field named 
radius
 that specifies the radius of the fan (the default is
5).
 A 
string
 data field named 
color
 that specifies the color of the fan (the default is blue).
 The 
accessor
 and 
mutator
 methods for all four data fields.
 A 
no-arg constructor 
that creates a default fan.
 A method named 
toString()
 that returns a string description for the fan. If the fan is on, the
method returns the fan speed, color, and radius in one combined string. If the fan is not on,
the method returns the fan color and radius along with the string “fan is off” in one combined
string.
Write a test program that creates two Fan objects. Assign maximum speed, radius 10, color
yellow, and turn it on to the first object. Assign medium speed, radius 5, color blue, and turn it
off to the second object. Display the objects by invoking their toString method.
 
Program
 
(
The 
Rectangle 
class
) design a class named 
Rectangle 
to represent a
rectangle. The class contains:
 Two private 
double 
data fields named 
width 
and 
height 
that specify the
width and height of the rectangle. The default values are 
1 
for both 
width 
and
height
.
 A no-arg constructor that creates a default rectangle.
 A constructor that creates a rectangle with the specified 
width 
and
height
.
 The accessor and mutator methods for both data fields. They don’t allow to
set non-negative values.
 A method named 
getArea() 
that returns the area of this rectangle.
 A method named 
getPerimeter() 
that returns the perimeter.
 
Write a test program that creates two 
Rectangle 
objects—one with width 
4
and height 
40 
and the other with width 
3.5 
and height 
35.9
. Display the
width, height, area, and perimeter of each rectangle in this order.
 
Object Oriented Programming
 
33
Passing object to methods
Passing an object to a method is to pass
the reference of the object.
You can pass objects to methods. Like
passing an array, passing an object is
actually passing the reference of the
object.
Object Oriented Programming
34
Cont.
Java uses 
exactly one mode of passing
arguments
: pass-by-value.
In the preceding code, the value of
myCircle 
is passed to the 
printCircle
method. This value is a reference to a
Circle 
object.
TestPassObject.java
Object Oriented Programming
35
 
Array of objects
 
An array can hold objects as well as
primitive type values.
   
Circle[] circleArray = 
new 
Circle[
10
];
 To initialize 
circleArray
, you can use a
for 
loop like this one:
for 
(
int 
i = 
0
; i < circleArray.length; i++) {
circleArray[i] = 
new 
Circle(); }
An array of objects is actually an array of
reference variables.
 
Object Oriented Programming
 
36
 
Immutable objects and classes
 
Normally, you create an object and allow
its contents to be changed later.
However, occasionally it is desirable to
create an object whose contents cannot
be changed once the object has been
created. We call such an object as
immutable object 
and its class as 
immutable
class
.
The 
String 
class, for example, is
immutable.
 
Object Oriented Programming
 
37
 
Cont.
 
How to make class immutable?
If you deleted the setter method in the
CircleWithPrivateDataFields 
class, the
class would be immutable, because radius is
private and cannot be changed without a
setter method.
 
Object Oriented Programming
 
38
Scope of variable
The scope of instance and static variables is the
entire class, regardless of where the 
variables are
declared.
Instance and static variables in a class are referred
to as the 
class’s variables 
or 
data fields
.
A variable defined inside a method is referred to
as a 
local variable
.
The scope of a class’s variables is the entire class,
regardless of where the variables are declared.
A class’s variables and methods can appear in any
order in the class.
Object Oriented Programming
39
Cont.
You can declare a class’s variable only
once, but you can declare the same
variable name in a method many times in
different non-nesting blocks.
If a local variable has the same name as a
class’s variable, the local variable takes
precedence and the class’s variable with
the same name is 
hidden.
Object Oriented Programming
40
 
The this reference
 
The keyword 
this 
refers to the object
itself. It can also be used inside a
constructor to invoke another
constructor of the same class
.
 
Object Oriented Programming
 
41
 
Cont.
 
Using this to invoke constructor
 
 
 
 
 
 
 
It can be used to refer instance variable of current class
It can be used to invoke or initiate current class constructor
It can be passed as an argument in the method call
It can be passed as argument in the constructor call
It can be used to return the current class instance
Click to know the example… 
link
 
Object Oriented Programming
 
42
 
Object Oriented Thinking
 
The focus of this chapter/topic is on class
design and explores the differences
between procedural programming and
object-oriented programming.
Four main concepts in OOPs are
Abstraction, Encapsulation, Inheritance
and Polymorphism (AEIP)
 
Object Oriented Programming
 
43
Class abstraction
Class 
abstraction
 is the separation of class
implementation from the use of a class.
The creator of a class describes the
functions of the class and lets the user
know how the class can be used.
The collection of methods and fields that
are accessible from outside the class,
together with the description of how
these members are expected to behave,
serves as the 
class’s contract
.
Object Oriented Programming
44
 
What is the need for Data Abstraction?
 : If you
want to hide your business logic from the outside
world. To achieve this implementation we can use Data
Abstraction.
TV or Car remote 
is assembled from the collection of
circuits but they don't show to the user all circuits
behind the remote, They only provide remote to the
user to use it. When the user presses the key on
remote the channel gets changed. They provide only
necessary information to the user.
 
 
 
Cont.
 
Object Oriented Programming
 
45
 
Class encapsulation
 
The details of implementation are
encapsulated and hidden from the user.
This is 
known as class 
encapsulation
.
Class abstraction and encapsulation are
two sides of the same coin.
Many examples in real life shows the
concept of abstraction/encapsulation –
building computer system, mobile, car.
 
Object Oriented Programming
 
46
 
Cont.
 
What is the need for Data
Encapsulation? :  
If you want to hide the
complexity and provide the security to data.
To achieve this implementation the oops
concept came i.e. Data Encapsulation.
Remote is assembled from the collection of
circuits but they hide all circuits from the
user. They encapsulate all circuits in one
thing called remote and provide to the user
to use it. And also remote can provide
security to all circuits used inside the
remote.
 
Object Oriented Programming
 
47
Cont.
Abstraction hides details at the 
design
level, while Encapsulation hides details at
the 
implementation
 level.
Object Oriented Programming
48
 
Procedural lang. Vs. OOP lang.
 
ComputeLoan.java
That 
program cannot be reused in other
programs because the code for computing
the payments is 
in the 
main 
method.
One way to fix this problem is to define
static methods for computing the monthly
payment and total payment.
However, this solution has limitations.
Suppose you wish to associate a date with
the loan. There is no good way to tie a date
with a loan without 
using objects.
 
Object Oriented Programming
 
49
 
Cont.
 
Object Oriented Programming
 
50
 
TestLoanClass.java
 
Thinking in Objects
 
The procedural paradigm focuses on
designing methods.
The object-oriented paradigm couples
data and methods together into objects.
Software design using the object-oriented
paradigm focuses on objects and
operations on objects.
UseBMIClass.java
 
Object Oriented Programming
 
51
 
Class relationship
 
To design classes, you need to explore the
relationships among classes.
Designing stack class.  -
TestStackOfIntegers.java
 
Object Oriented Programming
 
52
 
Program - Queue
 
(
The 
Queue 
class
) Design a class named 
Queue 
for storing integers. Like a stack, a
queue holds elements. In a stack, the elements are retrieved in a last-in first-out fashion.
In a queue, the elements are retrieved in a first-in first-out fashion. The class contains:
 An private 
int[] 
data field named 
elements 
that stores the 
int 
values in the queue.
 A private data field named 
size 
that stores the number of elements in the queue.
 A constructor that creates a 
Queue 
object with default capacity 
8
.
 The method 
enqueue(int v) 
that adds 
v 
into the queue.
 The method 
dequeue() 
that removes and returns the element from the queue.
 The method 
empty() 
that returns true if the queue is empty.
 The method 
getSize() 
that returns the size of the queue.
Implement the class with the initial array size set to 8. The array size will be doubled
once the number of the elements exceeds the size.  After an element is removed from
the beginning of the array, you need to shift all elements in the array one position the
left.
Write a test program that adds 20 numbers from 1 to 20 into the queue and removes
these numbers and displays them.
 
Object Oriented Programming
 
53
 
Primitive data type values as object
 
A primitive type value is not an object,
but it can be wrapped in an object using a
wrapper class in the Java API.
Many Java methods require the use of
objects as arguments. Java offers a
convenient way to incorporate, or wrap, a
primitive data type into an object.
 
Object Oriented Programming
 
54
 
Cont.
 
By using a wrapper class, you can process
primitive data type values as objects.
Java provides 
Boolean
, 
Character
,
Double
, 
Float
, 
Byte
, 
Short
, 
Integer
,
and 
Long 
wrapper classes in the
java.lang 
package for primitive data
types.
 
Object Oriented Programming
 
55
Cont.
Numeric wrapper classes are very similar
to each other.
Each contains the methods
doubleValue()
, 
floatValue()
,
intValue()
, 
longValue()
, 
shortValue()
,
and 
byteValue()
. These methods
“convert” objects into primitive type
values.
Object Oriented Programming
56
How to construct wrapper object
Either from a primitive data type value or
from a string representing the numeric
value.
For example, 
new Double(5.0)
, 
new
Double("5.0")
, 
new Integer(5)
, and 
new
Integer("5")
.
The instances of all wrapper classes are
immutable; this means that, once the objects
are created, their internal values cannot be
changed.
Object Oriented Programming
57
 
Cont.
 
Each numeric wrapper class contains
methods like intValue(),doubleValue(),
floatValue() etc.
new Double(12.4).intValue() 
returns 
12
;
new Integer(12).doubleValue() 
returns 
12.0
;
compareTo() method
new Double(12.4).compareTo(new Double(12.3)) 
returns 
1
;
new Double(12.3).compareTo(new Double(12.3)) 
returns 
0
;
new Double(12.3).compareTo(new Double(12.51)) 
returns 
-1
;
 
Object Oriented Programming
 
58
 
Cont.
 
The numeric wrapper classes have a
useful static method, 
valueOf (String s)
.
This method creates a new object
initialized to the value represented by the
specified string. For example,
Double doubleObject = Double.valueOf(
"12.4"
);
Integer integerObject = Integer.valueOf(
"12"
);
 
Object Oriented Programming
 
59
 
Cont.
 
parseInt 
method in the 
Integer 
class to
parse a numeric string into an 
int 
value
and the 
parseDouble 
method in the
Double 
class to parse a numeric string
into a 
double 
value.
Integer.parseInt("11", 2) 
returns 
3
;
Integer.parseInt("12", 8) 
returns 
10
;
Integer.parseInt("13", 10) 
returns 
13
;
Integer.parseInt("1A", 16) 
returns 
26
;
Integer.parseInt("12", 2) 
would raise a runtime
exception because 
12 
is not a binary number.
 
Object Oriented Programming
 
60
Automatic conversion between
primitive type and wrapper object
A primitive type value can be automatically
converted to an object using a wrapper class,
and vice versa, depending on the context.
Converting a primitive value to a wrapper
object is called boxing. The reverse
conversion is called unboxing.
The compiler will automatically box a
primitive value that appears in a context
requiring an object, and will unbox an object
that appears in a context requiring a
primitive value. This is called 
autoboxing 
and
autounboxing.
Object Oriented Programming
61
 
Cont.
 
Object Oriented Programming
 
62
 
class
 
GFG
{
    public
 
static
 
void
 
main (String[] args)
    {
        // creating an Integer Object
        // with value 10.
        Integer i = new
 
Integer(10);
 
        // unboxing the Object
        int
 
i1 = i;
 
        System.out.println("Value of i: "
 
+ i);
        System.out.println("Value of i1: "
 
+ i1);
 
        //Autoboxing of char
        Character gfg = 'a';
 
        // Auto-unboxing of Character
        char
 
ch = gfg;
        System.out.println("Value of ch: "
 
+ ch);
        System.out.println("Value of gfg: "
 
+ gfg);
 
    }
}
BigInteger and BigDecimal class
The 
BigInteger 
and 
BigDecimal 
classes can be
used to represent integers or decimal numbers of
any size and precision.
If you need to compute with very large integers
or high-precision floating-point values, you can
use the 
BigInteger 
and 
BigDecimal 
classes in
the 
java.math 
package.
Both are immutable.
Use the 
add
, 
subtract
, 
multiply
, 
divide
, and
remainder 
methods to perform arithmetic
operations, and use the 
compareTo 
method to
compare two big numbers.
Object Oriented Programming
63
 
LargeFactorial.java
Cont.
There is no limit to the precision of a
BigDecimal 
object.
The 
divide 
method may throw an
ArithmeticException 
if the result
cannot be terminated. However, you can
use the overloaded 
divide(BigDecimal
d, int scale, int roundingMode)
method to specify a scale and a rounding
mode to avoid this exception.
Object Oriented Programming
64
 
String message = 
new 
String(
"Welcome
to Java"
);
String message = 
"Welcome to Java"
; -
also valid statement.
You can also create a string from an array
of characters –
char
[] charArray = {
'G'
, 
'o'
, 
'o'
, 
'd'
, 
' '
, 
'D'
, 
'a'
, 
'y'
};
String message = 
new 
String(charArray);
 
String class
 
Object Oriented Programming
 
65
 
The 
split 
method can be used to extract
tokens from a string with the specified
delimiters.
String[] tokens = 
"Java#HTML#Perl"
.split(
"#"
);
 
Cont.
 
Object Oriented Programming
 
66
 
Cont.
 
Strings are not arrays, but a string can be
converted into an array, and vice versa.
To convert a 
string into an array of
characters, use the 
toCharArray
method.
  
char
[] chars = 
"Java"
.toCharArray();
To convert a double value 5.44 to a string,
use String.valueOf(5.44). The return value
is a string consisting of the characters '5',
'.', '4', and '4'.
 
Object Oriented Programming
 
67
 
StringBuilder and StringBuffer
 
The StringBuilder and StringBuffer classes
are similar to the String class except that the
String class is immutable.
They are used wherever string class is used.
You can add, 
insert, or append new contents
into 
StringBuilder 
and 
StringBuffer
objects.
The 
StringBuilder 
class is similar to
StringBuffer 
except that the methods for
modifying the buffer in 
StringBuffer 
are
synchronized
, which means that only one task
is allowed to execute the methods.
 
Object Oriented Programming
 
68
Cont.
Use 
StringBuffer 
if the class might be
accessed by multiple tasks concurrently,
because synchronization is needed in this
case to prevent corruptions to StringBuffer.
The constructors and methods in
StringBuffer 
and 
StringBuilder 
are
almost the same.
You can replace 
StringBuilder 
in all
occurrences in this section by
StringBuffer
.
Object Oriented Programming
69
Cont.
 
Object Oriented Programming
70
Slide Note
Embed
Share

Object-oriented programming enables the effective development of large-scale software and GUIs by defining classes to represent entities in the real world as objects with unique identities, states, and behaviors. Objects have data fields representing their properties and methods defining their actions. Classes serve as templates for objects, allowing for instantiation and the use of constructors for object initialization.


Uploaded on Jul 18, 2024 | 2 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Objects and Class Object Oriented Programming 1

  2. Object Oriented Programming Object-oriented programming enables you to develop large-scale software and GUIs effectively. However, these Java features (whatever learnt so far) are not sufficient for developing graphical user interfaces and large-scale software systems. Suppose you want to develop a graphical user interface as shown below: Object Oriented Programming 2

  3. Defining classes for objects A class defines the properties and behaviors for objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. Object Oriented Programming 3

  4. Cont. An object has a unique identity, state, and behavior. The state of an object (also known as its properties or attributes) is represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizes a circle. A rectangle object has the data fields width and height, which are the properties that characterize a rectangle. The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action. For example, you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerimeter() to return its perimeter. You may also define the setRadius(radius) method. A circle object can invoke this method to change its radius. Object Oriented Programming 4

  5. Cont. A class is a template, blueprint, or contract that defines what an object s data fields and methods will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation. A Java class uses variables to define data fields and methods actions/behaviour. to define Object Oriented Programming 5

  6. Cont. Additionally, a class provides methods of a special type, known as constructors, which are invoked to create a new object. A constructor can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects. Object Oriented Programming 6

  7. Object Oriented Programming 7

  8. The above class is different from all the classes we have seen so far. The class which contains main method is called main class. Another way to write the same program SimpleCircle.java TestSimpleCircle.java Object Oriented Programming 8

  9. Cont. You can put the more than one classes into one file, but only one class in the file can be a public class. Furthermore, the public class must have the same name as the file name. Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public. Each class in the source code is compiled into a .class file. When you compile TestSimpleCircle.java, two class files TestSimpleCircle.class and SimpleCircle.class are generated. Object Oriented Programming 9

  10. Cont. In java file, more than one class may contain main method. So, we can invoke the main method of specific class as follow: >java a - this will call main method of class a >java b - this will call main method of class b Object Oriented Programming 10

  11. Cont. Consider television sets. Each TV is an object with states (current channel, current volume level, power on or off) and behaviors (change channels, adjust volume, turn on/off). You can use a class to model TV sets. TestTV.java Object Oriented Programming 11

  12. Constructor A constructor is invoked to create an object using the new operator. Constructors are a special kind of method. They have three peculiarities: A constructor must have the same name as the class itself. Constructors do not have a return type not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. Object Oriented Programming 12

  13. Cont. A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is referred to as a no-arg or no- argument constructor. A class may be defined without constructors. In this case, a public no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class. Object Oriented Programming 13

  14. Accessing object via reference variable An object s data and methods can be accessed through the dot (.) operator via the object s reference variable. Objects are accessed via the object s reference variables, references to the objects. Such variables are declared using the following syntax: ClassName objectRefVar; which contain Object Oriented Programming 14

  15. Cont. Accessing data field and method using dot operator. Reference field are set default to null. Object Oriented Programming 15

  16. Primitive type Vs Reference type Every variable represents a memory location that holds a value. Object Oriented Programming 16

  17. Using Classes from Java Library The Java API contains a rich set of classes for developing Java programs. Date class: Object Oriented Programming 17

  18. Cont. Random class: Math.random() Another way to generate random numbers is to use the java.util.Random class Object Oriented Programming 18

  19. Cont. Point2D class: Java API has a conveninent Point2D class in the javafx.geometry package for representing a point in a two- dimensional plane Object Oriented Programming 19

  20. Cont. Object Oriented Programming 20

  21. Static variable, constant and methods The radius in circle1 is independent of the radius in circle2 and is stored in a different memory location. Changes made to circle1 s radius do not affect circle2 s radius,and vice versa. Object Oriented Programming 21

  22. Cont. If you want all the instances of a class to share data, use static variables, also known as class variables. A static variable is shared by all objects of the same class. A static method cannot access instance members of the class. Static variables store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected. Java supports static methods as well as static variables. Static methods can be called without creating an instance of the class. Object Oriented Programming 22

  23. Cont. TestCircleWithStaticMembers.java Object Oriented Programming 23

  24. Visibility modifiers Visibility modifiers can be used to specify the visibility of a class and its members. You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access. Object Oriented Programming 24

  25. Cont. Packages can be used to organize classes. To do so, you need to add the following line as the first non comment and nonblank statement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package. Java recommends that you place classes into packages rather than using a default package. Object Oriented Programming 25

  26. Cont. The private modifier makes methods and data fields accessible only from within its own class. Object Oriented Programming 26

  27. Cont. If a class is not defined as public, it can be accessed only within the same package. Object Oriented Programming 27

  28. Cont. There is no restriction on accessing data fields and methods from inside the class. Object Oriented Programming 28

  29. Data field encapsulation Making data fields private protects data and makes the class easy to maintain. The data fields numberOfObjects CircleWithStaticMembers class in previous program can be modified directly. radius in and the Object Oriented Programming 29

  30. Cont. This is not a good practice for two reasons: First, data may be tampered with. For example, numberOfObjects is to count the number of objects created, but it may be mistakenly set to an arbitrary value (e.g., CircleWithStaticMembers.numberOfObjects = 10). Second, you want CircleWithStaticMembers ensure that the radius is nonnegative after other programs have already used the class. to modify class the to Object Oriented Programming 30

  31. Cont. A private data field cannot be accessed by an object from outside the class that defines the private field. So, how to make a private data field accessible: provide a getter method to return its value. To enable a private data field to be updated, provide a setter method to set a new value. A getter method is also referred to as an accessor and a setter to a mutator. TestCircleWithPrivateDataFields.java Object Oriented Programming 31

  32. Program (The Fan class) Design a class named Fan to represent a fan. The class contains: Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan speed. A private int data field named speed that specifies the speed of the fan (the default is SLOW). A private boolean data field named on that specifies whether the fan is on (the default is false). A private double data field named radius that specifies the radius of the fan (the default is 5). A string data field named color that specifies the color of the fan (the default is blue). The accessor and mutator methods for all four data fields. A no-arg constructor that creates a default fan. A method named toString() that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one combined string. If the fan is not on, the method returns the fan color and radius along with the string fan is off in one combined string. Write a test program that creates two Fan objects. Assign maximum speed, radius 10, color yellow, and turn it on to the first object. Assign medium speed, radius 5, color blue, and turn it off to the second object. Display the objects by invoking their toString method. Object Oriented Programming 32

  33. Program (The Rectangle class) design a class named Rectangle to represent a rectangle. The class contains: Two private double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height. A no-arg constructor that creates a default rectangle. A constructor that creates a rectangle with the specified width and height. The accessor and mutator methods for both data fields. They don t allow to set non-negative values. A method named getArea() that returns the area of this rectangle. A method named getPerimeter() that returns the perimeter. Write a test program that creates two Rectangle objects one with width 4 and height 40 and the other with width 3.5 and height 35.9. Display the width, height, area, and perimeter of each rectangle in this order. Object Oriented Programming 33

  34. Passing object to methods Passing an object to a method is to pass the reference of the object. You can pass objects to methods. Like passing an array, passing an object is actually passing the reference of the object. Object Oriented Programming 34

  35. Cont. Java uses exactly one mode of passing arguments: pass-by-value. In the preceding code, the value of myCircle is passed to the printCircle method. This value is a reference to a Circle object. TestPassObject.java Object Oriented Programming 35

  36. Array of objects An array can hold objects as well as primitive type values. Circle[] circleArray = new Circle[10]; To initialize circleArray, you can use a for loop like this one: for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); } An array of objects is actually an array of reference variables. Object Oriented Programming 36

  37. Immutable objects and classes Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. The String class, for example, is immutable. Object Oriented Programming 37

  38. Cont. How to make class immutable? If you deleted the setter method in the CircleWithPrivateDataFields class, the class would be immutable, because radius is private and cannot be changed without a setter method. Object Oriented Programming 38

  39. Scope of variable The scope of instance and static variables is the entire class, regardless of where the variables are declared. Instance and static variables in a class are referred to as the class s variables or data fields. A variable defined inside a method is referred to as a local variable. The scope of a class s variables is the entire class, regardless of where the variables are declared. A class s variables and methods can appear in any order in the class. Object Oriented Programming 39

  40. Cont. You can declare a class s variable only once, but you can declare the same variable name in a method many times in different non-nesting blocks. If a local variable has the same name as a class s variable, the local variable takes precedence and the class s variable with the same name is hidden. Object Oriented Programming 40

  41. The this reference The keyword this refers to the object itself. It can also be used inside a constructor to constructor of the same class. invoke another Object Oriented Programming 41

  42. Cont. Using this to invoke constructor It can be used to refer instance variable of current class It can be used to invoke or initiate current class constructor It can be passed as an argument in the method call It can be passed as argument in the constructor call It can be used to return the current class instance Click to know the example link Object Oriented Programming 42

  43. Object Oriented Thinking The focus of this chapter/topic is on class design and explores the differences between procedural programming and object-oriented programming. Four main concepts in OOPs are Abstraction, Encapsulation, Inheritance and Polymorphism (AEIP) Object Oriented Programming 43

  44. Class abstraction Class abstraction is the separation of class implementation from the use of a class. The creator of a class describes the functions of the class and lets the user know how the class can be used. The collection of methods and fields that are accessible from outside the class, together with the description of how these members are expected to behave, serves as the class s contract. Object Oriented Programming 44

  45. Cont. What is the need for Data Abstraction? : If you want to hide your business logic from the outside world. To achieve this implementation we can use Data Abstraction. TV or Car remote is assembled from the collection of circuits but they don't show to the user all circuits behind the remote, They only provide remote to the user to use it. When the user presses the key on remote the channel gets changed. They provide only necessary information to the user. Object Oriented Programming 45

  46. Class encapsulation The details of implementation are encapsulated and hidden from the user. This is known as class encapsulation. Class abstraction and encapsulation are two sides of the same coin. Many examples in real life shows the concept of abstraction/encapsulation building computer system, mobile, car. Object Oriented Programming 46

  47. Cont. What Encapsulation? : If you want to hide the complexity and provide the security to data. To achieve this implementation the oops concept came i.e. Data Encapsulation. Remote is assembled from the collection of circuits but they hide all circuits from the user. They encapsulate all circuits in one thing called remote and provide to the user to use it. And also remote can provide security to all circuits used inside the remote. is the need for Data Object Oriented Programming 47

  48. Cont. Abstraction hides details at the design level, while Encapsulation hides details at the implementation level. Object Oriented Programming 48

  49. Procedural lang. Vs. OOP lang. ComputeLoan.java That program cannot be reused in other programs because the code for computing the payments is in the main method. One way to fix this problem is to define static methods for computing the monthly payment and total payment. However, this solution has limitations. Suppose you wish to associate a date with the loan. There is no good way to tie a date with a loan without using objects. Object Oriented Programming 49

  50. Cont. TestLoanClass.java Object Oriented Programming 50

Related


More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#