Introduction to OOP with Java
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
OOP – Part 4
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
Lecture 10:
Instructor
• AbuKhleif, ‘Mohammad Noor’• Computer Engineer (JU 2012-2017)• Software Automation Engineer @ Atypon – John Wiley and
Sons Company - Jordan Branch
• Reach me at:• www.abukhleif.com• [email protected]• facebook.com/moh.noor94• twitter.com/moh_noor94
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
3
Course
• Java SE Basics• Object Oriented Programming• Course Page:
www.abukhleif.com/courses/java-101-sep-2017• Or, go to: www.abukhleif.com Courses Java 101 Course
– Sep 2017• Course Facebook Group:
www.facebook.com/groups/AKF2017Java
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
4
Immutable Objects and Classes
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
5
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.• Such an object is called immutable object and its class is called
immutable class.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
6
Immutable Objects and Classes
• For a class to be immutable, it must meet the following requirements:• All data fields must be private.
• There can’t be any mutator methods for data fields.
• No accessor methods can return a reference to a data field that is mutable.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
7
Example
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 8
public class Student {
private int id;
private String name;
private double[] grades;
public Student(int ssn, String newName) {
id = ssn;
name = newName;
grades = new double[3];
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double[] getGrades() {
return grades;
}
}
This method actually returns a reference to the array grades, which means it can be changed once returned.
Example,cont.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 9
public class test {
public static void main(String[] args) {
Student student = new Student(112233, “John”);
double[] studentGrades = student.getGrades();
studentGrades[0] = 90.0;
studentGrades[1] = 95.5;
studentGrades[2] = 92.9;
}
}
Let’s Code
• Rewrite the previous class to be immutable.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
10
Composition and Aggregation
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
11
Composition and Aggregation
• An object can contain another object. The relationship between the two is called composition.
• Composition is actually a special case of the aggregationrelationship.• Aggregation models has-a relationship and represents ownership
relationship between objects.
• The owner object is called an aggregating object.• And its class is called an aggregating class.
• The subject object is called an aggregated object.• And its class is called an aggregated class.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
12
Composition and Aggregation
• 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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
13
Name Address Student
Composition Aggregation
1 1..3 1 1
Composition and Aggregation
• An aggregation relationship is usually represented as a data field in the aggregating class.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
14
public class Name {
...
}
public class Student {
private Name name;
private Address address;
...
}
public class Address {
...
}
Aggregated class Aggregating class Aggregated class
Composition and Aggregation
• Aggregation may exist between objects of the same class.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
15
Person
Supervisor
1
1
public class Person { // The type for the data is the class itselfprivate Person supervisor; ...
}
Person
Supervisor
1
m
public class Person { // The type for the data is the class itselfprivate Person[] supervisors; ...
}
Let’s Code• Implement this class, using the Student class
example we studied before.
• Build a class ‘TestCourse’ to test your Course class.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
16
Course
-courseName: String
-students: String[]
-numberOfStudents: int
+Course(courseName: String)
+getCourseName(): String
+addStudent(student: String): void
+dropStudent(student: String): void
+getStudents(): String[]
+getNumberOfStudents(): int
The name of the course.
An array to store the students for the course.
The number of students (default: 0).
Creates a course with the specified name.
Returns the course name.
Adds a new student to the course.
Drops a student from the course.
Returns the students in the course.
Returns the number of students in the course.
Suggested Solution
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 17
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
// Left as an exercise
}
}
Suggested Solution
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com 18
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
course1.addStudent("Peter Jones");
course1.addStudent("Brian Smith");
course1.addStudent("Anne Kennedy");
course2.addStudent("Peter Jones");
course2.addStudent("Steve Smith");
System.out.println("Number of students in course1: "
+ course1.getNumberOfStudents());
String[] students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students[i] + ", ");
System.out.println();
System.out.print("Number of students in course2: "
+ course2.getNumberOfStudents());
}
}
Tips in OOP Design(Self Study)
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
19
Designing a Class
• (Coherence) A class should describe a single entity, and all the class operations should logically fit together to 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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
20
Designing a Class
• (Separating responsibilities) A single entity with too many responsibilities can be broken into several classes to separate responsibilities.
• The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities.
• The String class deals with immutable strings, the StringBuilderclass is for creating mutable strings, and the StringBuffer class is similar to StringBuilder except that StringBuffer contains synchronized methods for updating strings.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
21
Designing a Class
• 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, design the properties to ensure that the user can set properties in any order, with any combination of values, and design methods to function independently of their order of occurrence.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
22
Designing a Class
• Provide a public no-arg constructor and override the equalsmethod and the toString method defined in the Object class whenever possible.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
23
Designing a Class
• Follow standard Java programming style and naming conventions.
• Choose informative names for classes, data fields, and methods.
• Always place the data declaration before the constructor, and place constructors before methods.
• Always provide a constructor and initialize variables to avoid programming errors.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
24
Using Visibility Modifiers
• Each class can present two contracts• one for the users of the class, and• one for the extenders of the class.
• 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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
25
Using Visibility Modifiers
• The contract for the extenders encompasses the contract for the users.
• The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
26
Using Visibility Modifiers
• A class should use the private modifier to hide its data from direct access by clients.
• 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.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
27
Using the static Modifier
• A property that is shared by all the instances of the class should be declared as a static property.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
28
Homework
Homework
Part 1- Write a Java program that implements the classes shown in the following UML class diagram:
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
30
Homework
For the Item class, you are required to implement the following:
• A constructor that initializes the item name and price with the passed arguments.
• The mutator (set) method for the salesTax data field.
• The mutator (set) and accessor (get) methods for the price data field.
• The method getPriceWithTax which returns the price of the item including the tax.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
31
Homework
For the Market class you are required to implement the following:
• A constructor that initializes the name with the passed argument and create an array with 0 elements for the reference data field items.
• A constructor that initializes the name with the passed argument and create an array with the same number of elements of the passed array of items. Names and prices of items in the passed array should be copied to newly created objects in the new array.
• The method maxPrice which returns a reference to the item with the highest price.
• The method addItem which adds the passed item to the array items.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
32
Homework
Part 2- In your main class:
• Set the data field salesTax of the Item class to 0.14.
• Create an array with two items: • name: Chocolate, price: 0.5 • name: Rice, price: 4.0
• Create a market named “UJ” with these two items.
• Add the following item to the market: • name: Cheese, price: 1.3
• Print the name of the market, then the name and price of the item with the highest price, as follows:
“Market name: _______, item with highest price is ________ with price = _________.”
• For each item in the market, print the item name, price, and price with tax, as follows:
“Item name: _____, price: _________, price with tax:________”
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
33
Homework Submission
• Submit only the .java files.
• Upload your file to the Facebook group.
• Submission due: Thursday, Oct 5 - 08:00 PM
• Late submission will not be reviewed by the instructor.
• Public solutions upload goal is to share knowledge, you can see other’s solutions, but, please, don’t cheat yourself!
• Don’t forget, your solution should be well-documented, well-designed, and well-styled.
Introduction to OOP with Java - AbuKhleiF www.abukhleif.com
34
- Eng. Asma Abdel Karim Computer Engineering Department, JU Slides and Sheets.- Liang, Introduction to Java Programming 10/e
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
References:
End of Lecture =D