PART 2 Part 2: The Material. With the introduction of what an object is, now we are ready to learn the CONSTRUCTOR concept. And when we want to make use.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Fibonacci Numbers A simple example of program design.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
CSC 160 Computer Programming for Non-Majors Lecture #7: Variables Revisited Prof. Adam M. Wittenstein
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Introduction to Methods
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Object Oriented Software Development
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Object Oriented Programming Philosophy. Part 1 -- Basic Understanding & Encapsulation.
PART 4. We have now finished our introduction to the main concepts of object-oriented programming. More specifically, we have a good idea of what an object.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CS 350 – Software Design The Object Paradigm – Chapter 1 If you were tasked to write code to access a description of shapes that were stored in a database.
Java Classes Using Java Classes Introduction to UML.
4.1 Instance Variables, Constructors, and Methods.
Unit 3: Java Data Types Math class and String class.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
SharePoint document libraries I: Introduction to sharing files Sharjah Higher Colleges of Technology presents:
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
PART 3. You have been using static methods in your programs before and methods are the building blocks of procedural programming. In this part of the.
Functions Introduction to Programming By Engr. Bilal Ahmad 1ITP by Engr. Bilal Ahmad.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 6: Object-Oriented Programming.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
1 CS161 Introduction to Computer Science Topic #9.
ECSE Software Engineering 1I HO 4 © HY 2012 Lecture 4 Formal Methods A Library System Specification (Continued) From Specification to Design.
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
PART 1 Part 1: The Material. Whether you knew it or not, all the programming that you have performed until now was in the boundaries of procedural programming.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
COPYRIGHT 2010: Dr. David Scanlan, CSUS OBJECTIVES: How to write classes How to create an object from a class using the "New" keyword. How to communicate.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
CSE 143 Lecture 12 Inheritance slides created by Ethan Apter
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
OOP Basics Classes & Methods (c) IDMS/SQL News
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Summary prepared by Kirk Scott
Classes and Objects.
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
Error Handling Summary of the next few pages: Error Handling Cursors.
A simple example of program design
Phil Tayco Slide version 1.0 Created Oct 9, 2017
CMSC 202 Exceptions.
Presentation transcript:

PART 2 Part 2: The Material

With the introduction of what an object is, now we are ready to learn the CONSTRUCTOR concept. And when we want to make use of this Book class, we do the following: class Book { String title; String author; int year; } Just to refresh our memory, let’s take a look at what we have learned in part 1. A sample class declaration, as far as we have learned, looks like: Part 2: The Material

class Application { public static void main(String args[]) { Book book1 = new Book(); book1.title = “The Secret”; book1.year = 2006; book1.author = “Rhonda Byrne”; } Let’s say in another application, we want to create more than one book. Here is the code that creates two book objects and initializes the fields of each created object: Part 2: The Material

class Application { public static void main(String args[]) { Book book1 = new Book(); // Create the object book1.title = “The Secret”; // initalize the title field book1.year = 2006; // initialize the year field book1.author = “Rhonda Byrne”; // initialize the author field Book book2 = new Book(); book2.title = “Stuff on My Cat”; book2.year = 2006; book2.author = “Mario Garza”; } As you may have already noticed, we have written 8 lines of code just for creating and initalizing two book objects. What if the Book class had more than 3 fields? Then, it would be even longer to create and initalize a book object. Part 2: The Material

YES, there is! It is done using CONSTRUCTORS! Enough said, everything will become much clearer with an example. A constructor is a perfect candidate for initializing the fields of an object. You may think of constructors as methods that only get executed when the object gets created. That means, it only gets executed when the “new” keyword is used. In the previous examples, what we have done is:  First create the object by the Book book1 = new Book(); statement  Then go ahead and initialize the fields of the book object Constructors will allow us to initialize the fields AS we create the book object. Isn’t there a easier and cleanier way to create & initalize the fields of objects? Part 2: The Material

With this class declaration in hand, here is how we can make use of the constructor (the explanation will follow): class Book { String title; int year; String author; // The constructor! Book(String initialTitle, int initialYear, String initialAuthor) { title = initialTitle; year = initialYear; author = initialAuthor; } First let’s add the constructor to our Book class declaration: class Application { public static void main(String args[]) { // All in one line! Book book1 = new Book(“The Secret”, 2006, ” Rhonda Byrne”); } Part 2: The Material

OK, now it is time to analyze what we have done. First the constructor declaration: The first thing you will notice is the way you define a constructor. The name of the constructor should be identical to the class name. Since our class name was Book, the constructor name also gets to be Book. The second thing is the parameters of the constructors. The Book class has three fields that may be initalized. In correspondance with the number of fields, the constructor also takes in 3 parameters that will be initalized to the fields of the class. The third thing is that the constructors do not have any return type. That is a good way to distinguish constructors from methods: constructors cannot have a return type. Book(String initialTitle, int initialYear, String initialAuthor) { title = initialTitle; year = initialYear; author = initialAuthor; } Part 2: The Material

Now, let’s see how the constructor is used from an application. The following line is enough to execute the constructor: This single line says a lot. i) First, create a brand new book object. ii) And at the same time, make sure that the fields of the object are initialized to what I indicate in the parameters. Book book1 = new Book(“The Secret”, 2006, ” Rhonda Byrne”); So, it must be fairly easy to guess the output of the following code: class Application { public static void main(String args[]) { Book book1 = new Book(“The Secret”, 2006, ” Rhonda Byrne”); System.out.println(book1.title); } The Secret The constructor concept may have raised certain questions. Here are some sample questions and answers. Part 2: The Material

Q: What does actually happen when the Book book1 = new Book(“The Secret”, 2006, ” Rhonda Byrne”); line is executed? A: Let’s try to trace the code when the line gets executed. 1) Book book1 = new Book(“The Secret”, 2006, “Rhonda Byrne”); The new keyword here should remind you of a new object construction. Therefore, the constructor of the object will be executed. 2) Book( String initialTitle, int initialYear, String initialAuthor ) // in the class declaration The parameters of the constructors get their values. So, initialTitle = “The Secret” initialYear = 2006; initialAuthor = “Rhonda Byrne” 3) title = initialTitle; The title field of the object, gets the value of the initialTitle variable. Since initialTitle variable was previously set to “The Secret” in the second step, the title field of the object gets set to “The Secret”. 4) year = initialYear; // Same idea 5) author = initialAuthor; // Same idea Part 2: The Material

Q: Now I remember one of the first examples that I had done. I was able to create a book object using the Book book1 = new Book(); statement, but I am sure Book class didn’t have any constructors or anything like that. How was that possible? A: An excellent point! Here is the story behind that: Java is a very clever language. For creating a new object, you definitely need a constructor. Knowing that, if you did not put in any constructor, Java inserts a default (no additional functionality) constructor for your object. That means, when you did your exercise, your Book class declaration actually looked like: Part 2: The Material

class Book { String title; int year; String author; // The default constructor Book() { // no effect at all } Thanks to this default constructor, you were able to create a new Book object. However, obviously, this default constructor does not initalize any fields of the class. That was why previously you had to do it yourself. Part 2: The Material

Q: What about the number of constructors in a class? A: There is no limit on the number of constructors of a class. You could have as many as you want. Furthermore, it is a good idea to provide various options. For example, for the Book class you could also have these constructors: class Book { String title; int year; String author; Book(String initialTitle, int initialYear, String initialAuthor) { title = initialTitle; year = initialYear; author = initialAuthor; } Book(String initialTitle) { title = initialTitle; year = 0; author = “”; } Part 2: The Material

In the class declaration, you will notice the second constructor. It only asks for the title of the book and initalizes the title. Other fields will be initialized to default values. Here is how we may make use of the second constructor: class Application { public static void main(String args[]) { // We don’t know the author or the year of the book yet Book book1 = new Book(“The Secret”);... // We now learn the author and the year of the book book1.year = 2006; book1.author = “Rhonda Byrne”; } Our new constructor gave us an option. We have created the book object, assuming that we had only known the title of the book in the beginning. Therefore, we have used the constructor that solely initalizes the title of the book. Part 2: The Material

As a review, let’s make a comparison: Before Constructors class Application { public static void main(String args[]) { Book book1 = new Book(); book1.title = “The Secret”; book1.year = 2006; book1.author = “Rhonda Byrne”; Book book2 = new Book(); book2.title = “Stuff on My Cat”; book2.year = 2006; book2.author = “Mario Garza”; } class Application { public static void main(String args[]) { Book book1 = new Book(“The Secret”, 2006, ” Rhonda Byrne”); Book book2 = new Book(“ Stuff on My Cat ”, 2006, “ Mario Garza ”); } After Constructors Part 2: The Material

We have come a long way! We know have a good idea of what an object is and furthermore we know how to make use of the constructors of objects. Although it is relatively easy to grasp the notion of an object, one can easily get lost when examples get a little complicated. There is one specific example that seems to be the most confusing for the beginners: the idea of composition: having an object inside another object. The next 7-8 slides do not contain any new material. Instead, they are there to expand your vision about objects by working on a little more sophisticated problem. Knowing that, there will be an emphasis on this topic. The following slides will come up with examples in order to make sure that this example is well-understood. Part 2: The Material

So, what does it mean to have an object in an object? It would be best to explain this concept with an example. Imagine that you are taking an introductory object orientation course and you have received a new assignment from your professor. The assignment asks you to create a Person class. Here are the properties of the requested Person class: The name of the person, The age of the person, The job/occupation of the person The favorite book of the person Furthermore, the assignment provides the Book class implementation that we have seen in many parts of the tutorial. The specifications require you to make use of this Book class in your implementation of the Person class. Part 2: The Material

At first glance, the specifications may seem confusing. How can one make the connection between two different classes? Let’s start building our Person class without really thinking about the Book class implementation. It would look like: class Person { String name; int age; String occupation; // the book part that we are not sure of yet // of what type should it be? Simply a String? Or something else? ??? favoriteBook; } At this point, referring back to the box analogy would be a great idea! Part 2: The Material

As a reminder, here is the box analogy that we have used in part 1: author Book Class Basically, the book class encapsulates three different information: title of the book, author of the book and the year of the book. The same idea will apply for the Person class. This time the Person class will actually include a reference a book object (explanation will follow). title favoriteBook Person Class occupation name year age author title year Part 2: The Material

According to the figure, here is the hiearchy:  Person A name (String) An occupation (String) An age (int)  A favorite Book A title (String) An author (String) The year (int) With the figure and the hiearchy in hand, let’s try to write the code for the Person class. Part 2: The Material

class Person { String name; int age; String occupation; Book favoriteBook; } class Book { String title; String author; int year; } Now, let’s add constructors for each class so that our solution looks nice. For the Book class: class Book { String title; String author; int year; Book(String initialTitle, String initialAuthor, int initialYear) { title = initialTitle; author = initialAuthor; year = initialYear; } Part 2: The Material

class Person { String name; String occupation; int age; Book favoriteBook; Person(String initialName, String initialOccupation, int initialAge, Book initialFavoriteBook) { name = initialName; occupation = initialOccupation; age = initialAge; favoriteBook = initialFavoriteBook; } Until now, this was the most complicated code that we have written! We know have two nice classes, let’s use them in an application! Part 2: The Material

class Application { public static void main(String args[]) { Book book = new Book(“The Secret”, “Rhonda Byrne”, 2006); Person me = new Person(“Anıl”,”Student”,18,book); System.out.println(“My name is: “ + me.name); System.out.println(“I am “ + me.age + “ years old.”); System.out.println(“I am a “ + me.occupation); System.out.println(“The title of my favorite book is: ” + me.favoriteBook.title); } What about creating yourself using the Person class! Here is an application that does that: The last line says the following: “ The title of the favorite book of the person” Part 2: The Material

Let’s use the following diagram to show how one can access the title of the favorite book of a person.  Person A name (String) An occupation (String) An age (int)  A favorite Book A title (String) An author (String) The year (int) 1 2 So, this was the whole idea behind the object inside an object concept. There is one last minor detail that has to be covered, before finishing this second part of the tutorial. me.favoriteBook me.favoriteBook.title Part 2: The Material

Q: There were certain occasions in which we didn’t want to attach any particular value to a variable/field. For example, we had a name field which referred to the name of a person. If we didn’t know the name of the person, then we just typed name = “ ” to indicate that the name is unkown. Now with the last example, we could have a case where we have a person but we don’t really know the favorite book of that person. In that case, how can we state that the favorite book is unknown? Would favoriteBook = “ ” help? A: The suggested syntax, unfortunately, won’t be valid. Instead, we will make use of a brand new keyword for indicating that the favorite book is unknown. The keyword is: null Part 2: The Material

Let’s again try to create another person. Let this person be a friend of yours. However this time, unfortunately, you don’t really know the favorite book of your friend. How would you create your friend? class Application { public static void main(String args[]) { Person myFriend = new Person(“Anıl”,”Student”,18,null); System.out.println(“My name is: “ + me.name); System.out.println(“I am “ + me.age + “ years old.”); System.out.println(“I am a “ + me.occupation); } When you create your friend, instead of passing a book object to the constructor, you type null. That simply means: “I have no idea about the book, so I am giving you nothing”. Part 2: The Material

Until now, we have made an introduction to object-oriented programming and we have made a lot progress on the object concept. Now, it is a good time to take a step back a little and take a look at the big picture. Why almost every software company in the world makes use of Object-Oriented programming? What makes Object-Oriented programming unique? How is it different than procedural programming? What capabilities does it provide? By the end of this tutorial, you will have complete answers for these questions. For right now, let’s just start with one aspect of Object-Oriented programming: How it helps people to share or re-use the codes that they have written. Part 2: The Material

Let’s imagine that your professor wants you to write a small application for the school library. The users of this application must be able to browse the books in the library and see if they are available or not. class Book { String title; String author; int year; } Remember the book example from the first part of the tutorial? Here is the code for the Book class that we have written previously: In your library application, you will most probably need to store the title and author of the books in the library. Since you have already performed a similar task and created this Book class, it would be a very good idea to re-use this code. Part 2: The Material

Or, similarly, let’s say that a friend of yours is asking your help. S/he is working on a project and s/he knows that you had been working on a library application. S/he is asking if you have previously written a Book class so that s/he can use it in his/her project. If you agree to share your code, then all you have to do is send him/her the Book.java (the code below) class along with a simple documentation that describes your implementation of a Book. This is an example of how you could share your code with someone else. All your friend has to do right now is to add the Book.java class to his/her project, read its documentation and start using the Book object. There isn’t even a need to look at your code! class Book { String title; String author; int year; } Part 2: The Material

Let’s do some brainstorming and try to imagine what would happen if you didn’t use Object-Oriented programming. Would you be able to share your code with your friend? Without object-orientation your original code would most probably look like: class Application { public static void main(String args[]) { String book1Title = “”; String book1Author = “”; int book1Year = 0; // more code here..... } Part 2: The Material

This code wouldn’t be a good candidate for sharing. In order to make use of your code, your friend first has to analyze your code. Then, s/he has to understand how you have chosen to represent a book. And even after that, s/he will have to copy and paste those parts that she is interested in. As a result, it could be concluded that procedural programming doesn’t really support sharing / re-using of code in a nice way. Of course, these were very simple examples that emphasize on how object-oriented programming facilitates code reuse and code sharing. Try to imagine how nice it would be if the shared code contained thousands of lines! Part 2: The Material

This is indeed how giant projects (for example Microsoft Office) are implemented! Speficially, let’s think about the spelling functionality provided by Microsoft Word. With the help of object-orientation, the same spelling functionality can be easily re-used in Microsoft Outlook to spell-check our s. Millions of people do programming. That means billions of lines of code are written. One capability of object-orientation is to increase the re-usability of these codes, so that better and bigger projects could be implemented. - End of the Material for Part 2 - Part 2: The Material

Review of Concepts  Constructors are useful structures that help to initialize the fields of an object.  The constructor of an object is automatically called as the object gets created.  A constructor can accept parameters, which may be used to initialize the fields of the object.  In order to come up with more complicated data structures, an object may have another object as one of its field.  Such a composition allows the construction of bigger and better classes.  Object-oriented programming facilitates the code sharing among the people. An object created by one person, may easily be re-used by someone else when both people speak in terms of objects.  The sharing of object-oriented code, supported by a good documentation, greatly helps the construction of large-scaled projects. Part 2: The Review

Review of Syntax  Adding a constructor to a class declaration: Classname(parameters) { // your code goes here } 1.Constructor name = Class name 2.No return type!  When the value of an object is unknown, you may use the null keyword. e.g. favoriteBook = null Part 2: The Review

Exercise  We want you to model an employee, with the following properties:  An employee should have a name and surname  An employee should have a social insurance number  The birthdate of the employee should be stored for insurance purposes  Similarly, the system should also know that date that the employee is hired  It is indicated that the dates are very important for this application. Therefore, the dates will be stored in detail with the following properties  The year  The month  The day Part 2: The Exercise

Exercise (continued)  For each class that you have created, you should have appropriate constructors.  To show that you are capable of the classes you have designed, create a very simple application.  In the application do the following: 1.Create an employee named Alan Smith. 2.His birth date is 2 nd of September His social insurance number is He has been hired by his company on the 8 th of March Part 2: The Exercise

Solution class Date { // the fields of the Date class int year; int month; int day; // the constructor that initializes all the fields Date(int initialYear, int initialMonth, int initialDay) { year = initialYear; month = initialMonth; day = initialDay; } Part 2: The Solution

Solution (continued) class Employee { // the fields of the Employee class String name; String surname; String insuranceNumber; Date birthDate; Date hireDate; // the constructor that initializes all the fields Employee(String initialName, String initialSurname, String initialNumber, Date initialBirthDate, Date initialHireDate) { name = initialName; surname = initialSurname; insuranceNumber = initialNumber; birthDate = initialBirthDate; hireDate = initialHireDate; } Part 2: The Solution

Solution (continued) class Application { public static void main(String args[]) { Date birth = new Date(1974,9,2); Date hiring = new Date(2005,3,8); Employee employee = new Employee(“Alan”, “Smith”, “ ”, birth, hiring ) } Part 2: The Solution