0% found this document useful (0 votes)
37 views63 pages

Lecture 17 18 19 More On Objects

The document provides an overview of object-oriented programming concepts like immutable objects, this keyword, composition, aggregation, inheritance, encapsulation, and abstraction. It discusses how immutable objects cannot be changed once created and provides examples. It also explains the uses of the this keyword, composition vs aggregation relationships, and how abstraction separates class implementation from its use.

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views63 pages

Lecture 17 18 19 More On Objects

The document provides an overview of object-oriented programming concepts like immutable objects, this keyword, composition, aggregation, inheritance, encapsulation, and abstraction. It discusses how immutable objects cannot be changed once created and provides examples. It also explains the uses of the this keyword, composition vs aggregation relationships, and how abstraction separates class implementation from its use.

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Lecture-16

By
Dr. Bharati Mishra
Objectives
• Chapter 10
• Immutable objects
• this keyword
• Composition
• Differences between procedural programming &
OOP
• Guidelines for OOP
More on Objects
Immutable
• Immutable object:
• If the contents of an object cannot be changed
once the object is created
• Its class is called an immutable class.

Circle3
Immutable
• A class with all private data fields and
without mutators is not necessarily
immutable.
• Example: next slide (Student class)
Example..

public class BirthDate {


private int year;
private int month;
private int day;

public BirthDate(int newYear,int newMonth,int


newDay) {
year = newYear;
month = newMonth;
day = newDay;
}

public void setYear(int newYear) {


year = newYear;
}
}
Example
public class Student {
private int id;
private BirthDate birthDate;

public Student(int ssn,int year, int month, int day)

{
id = ssn;
birthDate = new BirthDate(year, month, day);
}

public int getId() {


return id;
}

public BirthDate getBirthDate() {


return birthDate;
}
}
Example …

public class Test {


public static void main(String[] args) {
Student student = new Student(111223333,1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is
// changed!
}
}

8
Immutable
• For a class to be immutable, it must
1. Mark all data fields private
2. Provide no mutator methods
3. Provide no accessor methods that would
return a reference to a mutable data field
object.
Scope
Variable Scope

• The scope of instance and static data fields


is the entire class.
• They can be declared anywhere inside a
class.
• The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable.
• A local variable must be initialized explicitly
before it can be used.
Variable Scope

• Example
Variable Scope

• 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.
Variable Scope

• Example
this Keyword
this

• The this keyword is the name of a reference


that refers to an object itself.
• One common use of the this keyword is
reference a class’s hidden data fields.
• Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
this

• Using this to reference hidden fields


this

• Use this to call overloaded constructor


Class Relationships
Association
Aggregation
Composition
Inheritance

Association: is a general binary relationship that describes


an activity between two classes.

19
Composition & Aggregation
Composition

• An object can contain another object.


• The relationship between the two is called
composition.
Aggregation

• Composition is a special case of the


“aggregation” relationship.
• Aggregation models “has-a” relationships.
• The owner object is called an aggregating
object.
• The subject object is called an aggregated
object.
Composition

• An object may be owned by several other


aggregating objects.
• If an object is exclusively owned by an
aggregating object, the relationship
between them is referred to as
“composition”.
Example

• “a student has a name”


• A composition relationship
• “a student has an address”
• An aggregation relationship
• An address may be shared by several
students.
UML

• UML composition & aggregation notation


UML

• Each class involved in a relationship may


specify a multiplicity.
• A multiplicity could be a number or an interval
that specifies how many objects of the class
are involved in the relationship.
• The character * means an unlimited number of
objects
• The interval m..n means that the number of
objects should be between m and n, inclusive.
UML

• An aggregation relationship is usually


represented as a data field in the
aggregating class.
UML

• Aggregation may exist between objects of


the same class.
UML

• Aggregation may exist between objects of


the same class.
Class Abstraction
OOP

• Procedural programming
• Methods
• OOP
• Entities grouping related methods and data
Class Abstraction

• Class abstraction means to separate class


implementation from the use of the class.
• The user of the class does not need to
know how the class is implemented.
Class Abstraction

• Example: Loan class


Loan
-annualInterestRate: double The annual interest rate of the loan (default: 2.5).
-numberOfYears: int The number of years for the loan (default: 1)
The loan amount (default: 1000).
Loan
-loanAmount: double
-loanDate: Date The date this loan was created.

+Loan() Constructs a default Loan object. TestLoanClass


+Loan(annualInterestRate: double, Constructs a loan with specified interest rate, years, and
numberOfYears: int, loan amount.
loanAmount: double)
+getAnnualInterestRate(): double Returns the annual interest rate of this loan. Run
+getNumberOfYears(): int Returns the number of the years of this loan.
+getLoanAmount(): double Returns the amount of this loan.
+getLoanDate(): Date Returns the date of the creation of this loan.
+setAnnualInterestRate( Sets a new annual interest rate to this loan.
annualInterestRate: double): void
+setNumberOfYears( Sets a new number of years to this loan.
numberOfYears: int): void
+setLoanAmount( Sets a new amount to this loan.
loanAmount: double): void
+getMonthlyPayment(): double Returns the monthly payment of this loan.
+getTotalPayment(): double Returns the total payment of this loan.
Class Abstraction

• Example: BMI
BMI
The get methods for these data fields are
provided in the class, but omitted in the
UML diagram for brevity.
UseBMIClass
BMI
-name: String The name of the person.
-age: int The age of the person. Run
-weight: double The weight of the person in pounds.
-height: double The height of the person in inches.

+BMI(name: String, age: int, weight: Creates a BMI object with the specified
double, height: double) name, age, weight, and height.
+BMI(name: String, weight: double, Creates a BMI object with the specified
height: double) name, weight, height, and a default age
20.
+getBMI(): double Returns the BMI
+getStatus(): String Returns the BMI status (e.g., normal,
overweight, etc.)
Class Abstraction

• Example: Course
Course

TestCource

Course
-name: String The name of the course.
-students: String[] The students who take the course.
-numberOfStudents: int The number of students (default: 0).
+Course(name: String) Creates a Course with the specified name.
+getName(): String Returns the course name.
+addStudent(student: String): void Adds a new student to the course list.
+getStudents(): String[] Returns the students for the course.
+getNumberOfStudents(): int Returns the number of students for the course.
Class Abstraction

• Example: Designing Stack

Push Pop

Z
Y
x
Class Abstraction

• Example: Stack
StackOfIntegers
-elements: int[] An array to store integers in the stack.
-size: int The number of integers in the stack.
+StackOfIntegers() Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int) Constructs an empty stack with a specified capacity.
+empty(): boolean Returns true if the stack is empty.
+peek(): int Returns the integer at the top of the stack without
removing it from the stack.
+push(value: int): int Stores an integer into the top of the stack.
+pop(): int Removes the integer at the top of the stack and returns it.
+getSize(): int Returns the number of elements in the stack.

TestStackOfIntegers Run
Class Abstraction

• Example: Designing Stack

StackOfIntegers
Class Abstraction

• Example: Guess Date

GuessDate UseGuessDateClass Run


Class Design Guidelines
Guideline

• Coherence
• A class should describe a single entity
• All the class operations should support a
coherent purpose.
• You can use a class for students, for
example, but you should not combine
students and staff in the same class,
because students and staff have different
entities.
Guideline

• A single entity with too many


responsibilities can be broken into several
classes to separate responsibilities.
Guideline

• Classes are designed for reuse. Users can


incorporate classes in many different
combinations, orders, and environments.
• Therefore, you should design a class that
imposes no restrictions on what or when
the user can do with it.
Guideline

• Design the properties to ensure that the


user can set properties in any order, with
any combination of values.
• Design methods to function independently
of their order of occurrence.
Guideline

• Provide a public no-arg constructor and


override the equals method and the toString
method defined in the Object class
whenever possible.
Guideline

• Follow standard Java programming style and


naming conventions.
• Choose informative names for classes, data
fields, and methods.
Guideline

• Always place the data declaration before the


constructor, and place constructors before
methods.
• Always provide a constructor and initialize
variables to avoid programming errors.
Guideline

• Make the fields private and accessor


methods public if they are intended for the
users of the class.
• Make the fields or method protected if they
are intended for extenders of the class
(more on extension and inheritance later).
Guideline

• You can use get methods and set methods


to provide users with access to the private
data, but only to private data you want the
user to see or to modify.
• A class should also hide methods not
intended for client use.
Guideline

• A property (data field) that is shared by all


the instances of the class should be declared
as a static property.
Wrapper Classes
Wrapper Classes
• Java provides 8 primitive data types: byte, short, int, long, float,
double, boolean, char
• One of the limitations of the primitive data types is that we
cannot create ArrayLists of primitive data types.
• However, this limitation turns out not to be very limiting after
all, because of the so-called wrapper classes:
• Byte, Short, Integer, Long, Float, Double, Boolean, Character
• These wrapper classes are part of java.lang (just like String and
Math) and there is no need to import them.

9-52
Wrapper Classes Examples
• Creating a new object:
Integer studentCount = new Integer(12);

• Changing the value stored in the object:


studentCount = new Integer(20);

• Getting a primitive data type from the object:


int count = studentCount.intValue();

9-53
Auto Boxing / UnBoxing

• You can also assign a primitive value to a wrapper class


object directly without creating an object. This is called
Autoboxing
Integer studentCount = 12;

• You can get the primitive value out of the wrapper class
object directly without calling a method (as we did
when we called .intValue()). This is called Unboxing

System.out.println(studentCount);

9-54
Wrapper Classes and ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner k = new Scanner(System.in);
System.out.println("Enter some non-zero integers. Enter 0 to end.");
int number = k.nextInt();
while (number != 0)
{
list.add(number); // autoboxing happening here
number = k.nextInt();
}

System.out.println("Your numbers in reverse are:");


for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i)); // unboxing happening here
}
9-55
Examples
The Parse Methods
• One of the useful methods on the Wrapper classes is the parse
methods. These are static methods that allow you to convert a
String to a number.

• Each class has a different name for its parse method:


• The Integer class has a parseInt method that converts a String to an int

• The Short class has a parseShort method that converts a String to a Short

• The Float class has a parseFloat method that converts a String to a Float

• Etc.

9-57
The Parse Methods Examples
byte b = Byte.parseByte("8");
short sVar = Short.parseShort("17");
int num = Integer.parseInt("28");
long longVal = Long.parseLong("149");
float f = Float.parseFloat("3.14");
double price = Double.parseDouble("18.99");

• If the String cannot be converted to a number, an exception is


thrown. We will discuss exceptions later.

9-58
Helpful Methods on Wrapper Classes
• The toString is static method that can convert a number back to a
String:

int months = 12;


double PI = 3.14;
String monthsStr = Integer.toString(months);
String PIStr = Double.toString(PI);

• The Integer and Long classes have three additional methods to


do base conversions: toBinaryString, toHexString, and
toOctalString

int number = 16;


System.out.print(Integer.toBinaryString(number) + “ “ +
Integer.toHexString(number) + “ “ + Integer.toOctalString(number));

• output: 10000 10 20

9-59
Helpful Static Variables on Wrapper Classes
• The numeric wrapper classes each have a set of static final
variables to know the range of allowable values for the data
type:
• MIN_VALUE
• MAX_VALUE

System.out.println("The minimum val for an int is “ +


Integer.MIN_VALUE);

System.out.println("The maximum val for an int is “ +


Integer.MAX_VALUE);

9-60
The Static valueOf Methods
The numeric wrapper classes have a useful
class 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");

61
61
BigInteger and BigDecimal
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. Both extend the Number
class and implement the Comparable interface.

62
62
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
LargeFactorial Run

BigDecimal a = new BigDecimal(1.0);


BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
63
63

You might also like