OOP Part 2. Introduction to OOP with Java. Lecture 08: Introduction to OOP with Java - AKF Sep AbuKhleiF -

Similar documents
Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Chapter 8 Objects and Classes

Chapter 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction. Introduction to OOP with Java. Lecture 01: Introduction to OOP with Java - AKF Sep AbuKhleiF -

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

UFCE3T-15-M Object-oriented Design and Programming

OO Programming Concepts

Chapter 9. Objects and Classes

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

ECOM 2324 COMPUTER PROGRAMMING II

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Chapter 3 Objects and Classes

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Object-Oriented Programming Concepts

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Chapter 8 Objects and Classes

Programming in the Large II: Objects and Classes (Part 1)

2 What are the differences between constructors and methods?

Object Oriented Programming in C#

Object Oriented Programming. Java-Lecture 1

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

CH. 2 OBJECT-ORIENTED PROGRAMMING

Recommended Group Brainstorm (NO computers during this time)

Chapter 8 Objects and Classes Part 1

CS 113 PRACTICE FINAL

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Inheritance and Polymorphism

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Oracle 1Z Java SE 8 Programmer I. Download Full Version :

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Computer Science II (20073) Week 1: Review and Inheritance

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CS 170, Section /3/2009 CS170, Section 000, Fall

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Questions Answer Key Questions Answer Key Questions Answer Key

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

Chapter 11 Inheritance and Polymorphism

University of Palestine. Mid Exam Total Grade: 100

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018

Introduction to Classes and Objects

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

CS1004: Intro to CS in Java, Spring 2005

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Introduction to Java. Handout-1d. cs402 - Spring

Comments are almost like C++

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Object Oriented Programming

Making New instances of Classes

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Creating and Using Objects

Lecture 10 Declarations and Scope

Last lecture. Lecture 9. in a nutshell. in a nutshell 2. Example of encapsulation. Example of encapsulation. Class test. Procedural Programming

Chapter 14 Abstract Classes and Interfaces

CS141 Programming Assignment #4

Exception-Handling Overview

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Classes and Objects. CGS 3416 Spring 2018

Programming by Delegation

Questions Answer Key Questions Answer Key Questions Answer Key

Documenting, Using, and Testing Utility Classes

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

EECS168 Exam 3 Review

Computer Science II Data Structures

ITI Introduction to Computing II

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

CS1150 Principles of Computer Science Objects and Classes

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Questions Answer Key Questions Answer Key Questions Answer Key

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Assignment Marking Criteria

Simple Java Reference

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CS61B Lecture #7. Announcements:

Introduction to Classes and Objects How to manage data and actions together. Slides #10: Chapter

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Reusing Classes. Hendrik Speleers

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Transcription:

Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 08: OOP Part 2 Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1

Instructor AbuKhleif, Mohammad Noor Computer Engineer (JU 2012-2017) Software Automation Engineer @ Atypon John Wiley and Sons Company - Jordan Branch Reach me at: moh.noor94@gmail.com facebook.com/moh.noor94 twitter.com/moh_noor94 3 Course Java SE Basics Object Oriented Programming Course Page: /courses/java-101-sep-2017 Or, go to: Courses Java 101 Course Sep 2017 Course Facebook Group: www.facebook.com/groups/akf2017java 4 AbuKhleiF - 2

Static Variables, Constants, and Methods 5 Static Variables, Constants, and Methods All variables declared in the data fields of the previous examples are called instance variables. An instance variable is tied to a specific instance of the class. It is not shared among objects of the same class. It has independent memory storage for each instance. 6 AbuKhleiF - 3

Static Variables, Constants, and Methods In the following example, the radius of the first object circle1 is independent of the radius of the second object circle2 : Circle circle1 = new Circle(); Circle circle2 = new Circle(5); 7 Static Variables, Constants, and Methods Static variables, also known as class variables, store values for the variables in a common memory location. A static variable is used when it is wanted that all instances of the class to share data. If one instance of the class changes the value of a static variables, all instances of the same class are affected. Static methods can be called without creating an instance of the class. 8 AbuKhleiF - 4

Static Variables, Constants, and Methods To declare a static variable or define a static method, put the modifier static in the variable or method declaration. Since constants in a class are shared by all objects of the class, they should be declared static. final static double PI = 3.14159265358979323846; Static variables and methods can be accessed from a reference variable or from their class name. 9 Welcome to Java Program - Revisit // This program prints Welcome to Java! public class Welcome { public static void main(string[] args) { System.out.println("Welcome to Java!"); 10 AbuKhleiF - 5

public class CircleWithStaticMembers { /** The radius of the circle */ double radius; final static double PI = 3.14159265358979323846; /** The number of the objects created */ static int numberofobjects = 0; /** Construct a circle with radius 1 */ CircleWithStaticMembers() { radius = 1.0; numberofobjects++; /** Construct a circle with a specified radius */ CircleWithStaticMembers(double newradius) { radius = newradius; numberofobjects++; Example /** Return numberofobjects */ static int getnumberofobjects() { return numberofobjects; /** Return the area of this circle */ double getarea() { return radius * radius * PI; 11 public class TestCircleWithStaticMembers { /** Main method */ public static void main(string[] args) { System.out.println("Before creating objects"); System.out.println("The number of Circle objects is " + CircleWithStaticMembers.numberOfObjects); // Create c1 CircleWithStaticMembers c1 = new CircleWithStaticMembers(); // Display c1 BEFORE c2 is created System.out.println("\nAfter creating c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); // Create c2 CircleWithStaticMembers c2 = new CircleWithStaticMembers(5); // Modify c1 c1.radius = 9; Example // Display c1 and c2 AFTER c2 was created System.out.println("\nAfter creating c2 and modifying c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + c2.numberofobjects + ")"); 12 AbuKhleiF - 6

Example 13 UML Class Diagram: Static Members Example Circle radius: double numberofobjects: int getnumberofobjects(): int getarea(): double instantiate instantiate circle1 radius = 1 numberofobjects = 2 circle2 radius = 5 numberofobjects = 2 Memory 1 radius 2 5 radius numberofobjects After two Circle objects were created, numberofobjects is 2. Static members are underlined in UML class diagrams. 14 AbuKhleiF - 7

Relationship between Static and Instance Members An instance method can invoke and access static and instance members. A static method can only invoke and access static members. 15 Instance or Static? How to decide whether a variable or method should be an instance one or a static one? A variable or method that is dependent on a specific instance of the class should be an instance variable or method. Example: radius and getarea of the Circle class; each circle has its own radius and area. A variable or method that is not dependent on a specific instance of the class should be a static variable or method. Example: numberofobjects of the Circle class; all circles should share this value. 16 AbuKhleiF - 8

Let s Code Build a class that can count the number of instances of itself. Make 3 objects of this class and print the number of instances before and after each one. 17 Visibility Modifiers 18 AbuKhleiF - 9

Visibility Modifiers Visibility modifiers can be used to specify the visibility of a class and its members. A visibility modifier specifies how data fields and methods in a class can be accessed from outside the class. There is no restriction on accessing data fields and methods from inside the class. 19 Visibility Modifiers 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. 20 AbuKhleiF - 10

Packages Packages are used to organize classes. To do so, you need to add the following statement as the first 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. 21 Visibility Modifiers The public modifier can be used for classes, methods and data fields to denote that they can be accessed from any other classes. The private modifier makes methods and data fields accessible only from within its own class 22 AbuKhleiF - 11

Welcome to Java Program - Revisit // This program prints Welcome to Java! public class Welcome { public static void main(string[] args) { System.out.println("Welcome to Java!"); 23 Visibility Modifiers: Methods and Data Fields Example package p1; package p2; public class C1 { public int x; int y; private int z; public void m1() { void m2() { private void m3() { public class C2 { void amethod() { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; can invoke o.m1(); can invoke o.m2(); cannot invoke o.m3(); public class C3 { void amethod() { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); 24 AbuKhleiF - 12

Visibility Modifiers: Classes Example package p1; package p2; class C1 {... public class C2 { can access C1 public class C3 { cannot access C1; can access C2; 25 Visibility Modifiers: Note An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a). public class F { private boolean x; public static void main(string[] args) { F f = new F (); System.out.println(f.x); System.out.println(f.convert()); private int convert(boolean b) { return x? 1 : -1; (a) This is OK because object f is used inside the F class public class Test { public static void main(string[] args) { Foo f = new F(); System.out.println(f.x); System.out.println(f.convert(f.x)); (b) This is wrong because x and convert are private in F. 26 AbuKhleiF - 13

Visibility Modifiers: Conclusion The private modifier restricts access to within a class. The default modifier restricts access to within a package. The public modifier enables unrestricted access. The protected modifier (later). 27 UML Class Diagrams (2) 28 AbuKhleiF - 14

UML Class Diagrams Circle -radius: double -numberofobjects: int +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getnumberofobject(): int +getarea(): double The radius of this circle (default: 1.0). The number of circle objects created. Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the number of circle objects created. Returns the area of this circle. The (-) sign indicates a private modifier. The (+) sign indicates a public modifier. 29 Data Field Encapsulation 30 AbuKhleiF - 15

Data Field Encapsulation It is not a good practice to allow data fields to be directly modified. Data may be tampered with. The class becomes difficult to maintain and vulnerable to bugs. To prevent direct modifications of data fields, you should declare the data fields private. This is known as data field encapsulation. 31 Data Field Encapsulation A private data field cannot be accessed by an object from outside the class that defines the private field. However, a client often needs to retrieve and modify a data field. To make a private data field accessible: Provide a get method to return its value. Provide a set method set a new value to it. 32 AbuKhleiF - 16

Data Field Encapsulation A get method has the following signature: public returntype getpropertyname() If the returntype is boolean, the get method is defined as follows by convention: public boolean isproperyname() A set method has the following signature: public void setpropertyname(datatype propertyvalue) 33 IntelliJ IDEA Shortcuts Alt + Insert 34 AbuKhleiF - 17

public class CircleWithPrivateDataFields { /** The radius of the circle */ private double radius = 1; /** The number of the objects created */ private static int numberofobjects = 0; /** Construct a circle with radius 1 */ public CircleWithPrivateDataFields() { numberofobjects++; /** Construct a circle with a specified radius */ public CircleWithPrivateDataFields(double newradius) { radius = newradius; numberofobjects++; Example 35 /** Return radius */ public double getradius() { return radius; /** Set a new radius */ public void setradius(double newradius) { radius = (newradius >= 0)? newradius : 0; /** Return numberofobjects */ public static int getnumberofobjects() { return numberofobjects; /** Return the area of this circle */ public double getarea() { return radius * radius * Math.PI; These two methods are the only way to access the radius. This method is the only way to read the numberofobjects. numberofobjectsis only modified when a new object is created, there is no other way to modify it. Example 36 AbuKhleiF - 18

public class TestCircleWithPrivateDataFields { /** Main method */ public static void main(string[] args) { // Create a Circle with radius 5.0 CircleWithPrivateDataFields mycircle = new CircleWithPrivateDataFields(5.0); System.out.println("The area of the circle of radius " + mycircle.getradius() + " is " + mycircle.getarea()); // Increase mycircle's radius by 10% mycircle.setradius(mycircle.getradius() * 1.1); System.out.println("The area of the circle of radius " + mycircle.getradius() + " is " + mycircle.getarea()); Example 37 Let s Code Create a class called Date that includes three pieces of information as instance variables: A month (int), a day (int) and a year (int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displaydate that displays the month, day and year separated by forward slashes (/). Write a test application named DateTest that demonstrates classdate s capabilities. 38 AbuKhleiF - 19

Let s Code Create a class called Employee that includes three pieces of information as instance variables: A first name (String), a last name (String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. If the monthly salary is not positive, set it to 0.0. Provide a set and a get method for each instance variable. Write a test application named EmployeeTest that demonstrates class Employee s capabilities. Create two Employee objects and display each object s yearly salary. Then give each Employee a 10% raise and display each Employee s yearly salary again. 39 Homework AbuKhleiF - 20

Homework Part 1: Build a class called Utility that has methods to analyze a String parameter: One method can get you the number of occurrences of the and a in a String, Another one that finds if a String is a Palindrome, Another one that finds if a number is Armstrong. 41 Homework Part 2: Write a test application named UtilityTest that demonstrates class Utility capabilities. 42 AbuKhleiF - 21

Homework Submission Submit only the Utility.java file. Upload your file to the Facebook group. Submission due: Thursday, Sep 28-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, welldesigned, and well-styled. 43 References: - Eng. Asma Abdel Karim Computer Engineering Department, JU Slides. - Liang, Introduction to Java Programming 10/e Instructor: AbuKhleif, Mohammad Noor Sep 2017 End of Lecture =D AbuKhleiF - 22