Java Coding 5 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
Introduction to UML David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …Unified Modeling Language.
Java is an Object-Oriented Language b In structured programming languages, methods define the structure of the programs, they are basic building blocks.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Starting Chapter 4 Starting. 1 Course Outline* Covered in first half until Dr. Li takes over. JAVA and OO: Review what is Object Oriented Programming.
Object Oriented Software Development
Writing Classes (Chapter 4)
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Classes Methods Objects. Classes Classes We have been using classes ever since we started programming in Java Whenever we use the keyword class.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Advanced Programming in Java
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Object-Oriented Programming Concepts
Classes C++ representation of an object
Object Oriented Programming
Concepts of Object Oriented Programming
Programming Logic and Design Seventh Edition
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Java Coding – part 2 David Davenport Computer Eng. Dept.,
Objects as a programming concept
Classes and OOP.
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Chapter 3: Using Methods, Classes, and Objects
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Java LESSON 7 Objects, Part 1
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Inheritance Basics Programming with Inheritance
Defining Classes and Methods
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Java Coding 4 David Davenport Computer Eng. Dept.,
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Advanced Programming Behnam Hatami Fall 2017.
Computer Programming with JAVA
CS2011 Introduction to Programming I Objects and Classes
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Session 2: Introduction to Object Oriented Programming
CSE 1201 Object Oriented Programming
Encapsulation September 13, 2006 ComS 207: Programming I (in Java)
Workshop for Programming And Systems Management Teachers
Object-Oriented Programming
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Review of Previous Lesson
Review of Previous Lesson
Classes C++ representation of an object
CS 200 More Classes Jim Williams, PhD.
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Java Coding 6 David Davenport Computer Eng. Dept.,
C++ Object Oriented 1.
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Java Coding 5 David Davenport Computer Eng. Dept., To object or not… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Latest: 20/11/2017 ~ minor updates..? Previously: 17/11/2014 ~wow!

IMPORTANT… Students… Instructors… This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

From the beginning… History of programming paradigms GoTo Programming (spaghetti code!) Structured Programming Object-Oriented Programming ??? Aspect-Oriented ??? Functional… response to need to build ever larger programs correctly, on time & on budget [ 1950 - 1970 ] [ 1970 - 1990 ] [ 1990 – today?] Already seen how ideas inherent in top-down design & structured programming helped us (~with Robo programming). Design for change! ~ maintenance ~

Key Attributes of OOP Abstraction, Encapsulation, Inheritance, Polymorphism What? Ease of reuse Speeds implementation & facilitates maintenance. Component-based approach Easy to use existing code modules Easy to modify code to fit circumstances! A natural way to view/model world Makes design quicker, easier & less error-prone. OOP often said to be “Abstraction, Encapsulation, Inheritance & Polymorphism.” But can’t spell these let alone understand what they mean! So, in simple terms…

The world as we see it…? Look around & what do you see? Things? (books, chairs, tables, people…) Actually, claim we see individuals! Ayse, David, my textbook, that chair, Mehmet’s pencil, etc. The world is a set of individual things interacting with each other.

Describing the world (1) Describe a particular person Ayse has long blond hair, green eyes, is 1.63m tall, weighs 56Kg and studies computer engineering. Now lying down asleep. Mehmet studies electronics, has short black hair and brown eyes. He is 180cm and 75 kilos. Now running to class! Notice how all have specific values of name, height, weight, eye colour, state, … Describe some particular books; your textbooks for example. What features (properties & functionality) characterise a book? How about cars? Individual Category

Describing the world (2) Type/category determine an object’s properties & functionality Person has name, height, weight, can run, sleep, … Category gives default properties Saying “Ayse is a person with green eyes.” We infer/assume she has two of them, as well as two legs, arms, a nose, a mouth, hair, can speak, run, sleep, etc. Allows us to concentrate on “relevant” properties So, if I say “pages” you immediately think of newspapers or books or magazines. Note also, that we have categories of categories, e.g. living things, (animals (elephants, cats, dogs), person (student (undergrade, postgrade), faculty member( prof, assoc prof, assist prof), admin staff), furniture (living room, kitchen, bedroom), …) Notice too, that properties and property values are categories as well! Category Individual

Java OOP terminology Class - Category Properties/states Functionality/Services (examines/alters state) data methods object - Individual/unique thing (an instance of a class) Particular value for each property/state & functionality of all members of class. Class acts as blueprint for creating new objects Properties/states correspond to memory locations having particular values Functionality corresponds to the methods that examine/manipulate the property values

Java OOP Software Software System Set of objects Which interact with each other Created (instantiated) from class definitions One object will send a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done.) This corresponds to calling one of the second object’s methods! Person Set of objects are created in a main method (which is thus is like the world.) One or more objects are then “sent messages” asking them to do something (i.e. their methods are called.) They in turn, may create and/or send messages to other objects in other to achieve their task. Güneş: David – go to sleep, run to class (david changes state) Or Güneş asks florist to send flowers to frıend in Istanbul. Florist asks Güneş for x dollars. Güneşoffers credit card to florist. Florist asks bank to ok it which they do. Florist now asks another florist in Istanbul to deliver flowers to specified address. That florist asks delivery boy to take them. He finds house etc. Güneş has no idea about all this. The Ankara florist doesn’t know or care how flowers get delivered to house either! Objects need not be “real”. May have a date object, or a random number generator, or a string tokenizer, or webpage generator, or an error message, or … Sounds natural to ask person to do something for you, but in OOP you ask all sorts of objects to do things for you. eg. Ask a book to turn its page, ask a wallet to give you some money, a random number object to give you a random number, … main Güneş David David: Say your name “David”

In more detail Create & manipulate person objects Person name, age, salary, comments sayName, getNetSalary getComments setComments increaseAge … name: “Derya” age: 18 salary: 1000 comments: “” name: “David” age: 22 salary: 2000 comments: “Teaches CS101” name: “Güneş” age: 18 salary: 500 comments: “Good student” Mention UML too here… One Class… any number of objects!

Coding Java Classes // header public class Person { // properties // constructors // methods } String name; int age; double salary; String comments; public Person( String theName, int theAge ) { name = theName; age = theAge; comments = “”; } No main method here! Methods are not static (at least for now!) ? Define properties to be “private” Constructor – called when initialising new instances of class. Gives default values to properties. public void sayName() { System.out.println( name); }

“get” & “set” methods for some properties (no setName!) Coding Java Classes public String getName() { return name; } public String getComments() { return comments; } public void setComments( String someText) { comments = someText; } “get” & “set” methods for some properties (no setName!) public void increaseAge() { age = age + 1; } Important: Do not simply add variables used for temporary storage in a method, as a property! public double getNetSalary( int baseRate) { double tax; tax = compoundInterest( baseRate); return salary – tax * 1.10; } Variables which are not parameters or properties must be defined locally.

Creating & Using Objects Always Declare variable to “hold” object Create object using “new” statement Call object’s methods Person aStudent; aStudent = new Person( “Güneş”, 18); “Güneş” name: 18 age: 0.0 salary: “” comments: aStudent.sayName(); Given a class Person, can now create and use any number of instances of it. ? Just talk of box “holding” object or explicitly mention reference vs. object now? << NO Note SYNTAX: - previously STATIC – packageName.ClassName.methodName(params) - now INSTANCE – variableName.methodName(params) or objectName.methodName.(params) aStudent {Person} Put this in method of another class, (e.g main method)

Creating & Using Objects Person aStudent; aStudent = new Person( “Güneş”, 18); Person friend; friend = new Person( “David”, 22); “Güneş” name: 18 age: 0.0 salary: “” comments: aStudent {Person} “David” name: 22 age: 0.0 salary: “” comments: 23 friend {Person} “Good student” friend.increaseAge(); aStudent.setComments( “Good student”);

Simplified Person Class package myworld; // Person - simple example only! // Author: David, CS101 public class Person { // properties String name; int age; // constructors public Person( String theName, int theAge) { name = theName; age = theAge; } // methods public void increaseAge() { age = age + 1; public void sayNameAndAge() { System.out.println( name + "\t" + age ); Declare properties note private/package access. Give initial values to each of the properties Note: Do without package access to begin with. Demo ability to change properties directly, i.e. age = 101; Bad.. (breaks encapsulation), so either make properties private (not great since can restrict later extensions –next semester!) put in package and give protected or default access. Note: in demo, do without package first, this creates class file, mod code for package, compiler uses old class file! Delete it. Extend to include getName(); getAge(); toString(); equals( Person); Define (instance) methods that examine/change properties

Simplified PersonTest import myworld.Person; // PersonTest - demo Person class // Author: David, CS101 public class PersonTest { public static void main( String[] args) { // VARIABLES Person aStudent; Person friend; // PROGRAM CODE aStudent = new Person( "Güneş", 18); friend = new Person( "David", 22); aStudent.sayNameAndAge(); friend.sayNameAndAge(); friend.increaseAge(); aStudent.increaseAge(); System.out.println(); } } // end of class PersonTest Declare variables to hold Person objects Create Person objects & put them into the variables Use objects by calling their methods

Params vs. Properties… Resolving names / scope public Person( String theName, int theAge) { name = theName; age = theAge; } public Person( String theName, int age) { name = theName; age = age; } Show in demo. Java uses closest declaration of memory location, i.e. current scope first, then its outer scope… So…theName & theAge are in current scope (the parameters) Whereas… name & age are not… they are in outer scope (properties of class) When same names are used in both scopes… use keyword “this” to resolve (this refers to current instance, its properties & methods) Hence this.age refers to current age property, while age refers to parameter/local variable. public Person( String theName, int age) { name = theName; this.age = age; }

toString()… something special? // in main method try calling… System.out.println( p ); p.sayNameAndAge() ); System.out.println( p.getNameAndAge() ); System.out.println( p.toString() ); public void sayNameAndAge() { System.out.println( name + "\t" + age ); } Show in demo. Printed p first… no go because not initialised so created instance of it, then printed something funny, e.g. “Person@3cc7df92“ Then wrote sayNameAndAge() … ok, but not particularly reusable! So, write getNameAndAge() to return result as String… more useful! Now, method name doesn’t matter, does it… so could use xyz() ~maybe not! or toString() ~ok… notice what happens when printing p now? Java automatically calls “toString()” to get a String representation of an object. It’s one of a number of special methods… if you don’t write a method of the same name, Java gives a default one, which may or may not be useful! public String getNameAndAge() { return name + "\t" + age; } public String toString() { return name + " - " + age; }

Examples: existing classes Random class Random die; die = new Random(); int face = die.nextInt(6) + 1; System.out.println( face); StringTokenizer class Java provides lots of classes ready for us to use. Check the docs to see what the constructors and methods are. Strings are objects too ~just rather special ones in Java! If time permits, give second problem as exercise without objects first, then show object solution. Actually do the previous Person class example and a class that uses it. StringTokenizer tokens; tokens = new StringTokenizer( “to be or not to be”); while ( tokens.hasMoreTokens() ) { aWord = tokens.nextToken(); System.out.println( aWord); } System.out.println( “done”);

Jargon Class is a template/blueprint for creating objects/instances of its type Class has Properties, attributes, states, fields, … Methods, functionality, services, … Create/instantiate an instance/object of a class Constructor called automatically by “new”, to give initial values to all properties Also… instance variables & methods, each instance has own independent values for variables (as opposed to class variables & methods = static, & shared by all instances of class.) accessor & mutator (get & set) methods

More Jargon Accessor/get methods… (return value of property) Mutator/set methods… (changes value of property) Static vs. Instance (…before vs. after midterm!) an Instance… (an individual object of a class) Instance variables (its properties ~non-static) Instance methods (its non-static methods) Static/class variables… (shared by all instances) Static methods (or usable without objects!) Also… instance variables & methods, each instance has own independent values for variables (as opposed to class variables & methods = static, & shared by all instances of class.) accessor & mutator (get & set) methods