Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 5 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 5 David Davenport Computer Eng. Dept.,"— Presentation transcript:

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

2 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 saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 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 [ ] [ ] [ 1990 – today?] Already seen how ideas inherent in top-down design & structured programming helped us (~with Robo programming). Design for change! ~ maintenance ~

4 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…

5 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.

6 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

7 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

8 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

9 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”

10 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!

11 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); }

12 “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.

13 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)

14 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”);

15 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

16 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

17 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; }

18 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. 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; }

19 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”);

20 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

21 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


Download ppt "Java Coding 5 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google