1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

Slides:



Advertisements
Similar presentations
SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
Advertisements

Understanding class definitions Looking inside classes 5.0.
Looking inside classes Fields, Constructors & Methods Week 3.
Chapter 7: User-Defined Functions II
Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors.
Understanding class definitions Looking inside classes 3.0.
Object interaction Creating cooperating objects 3.0.
Programming with Objects Creating Cooperating Objects Week 6.
Object Interaction 1 Creating cooperating objects.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
1 Reflecting on the ticket machines Their behavior is inadequate in several ways: –No checks on the amounts entered. –No refunds. –No checks for a sensible.
Object interaction Creating cooperating objects 5.0.
Object interaction Creating cooperating objects 5.0.
Object Interaction 2 Creating cooperating objects.
Understanding class definitions Looking inside classes.
Object interaction Creating cooperating objects. 28/10/2004Lecture 3: Object Interaction2 Main concepts to be covered Abstraction Modularization Class.
Programming with Objects Object Interaction (Part 1) Week 9.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Programming Fundamentals 2: Interaction/ F II Objectives – –introduce modularization and abstraction – –explain how an object uses other.
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
Classes CS 21a: Introduction to Computing I First Semester,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
OBJECT INTERACTION CITS1001. Overview Coupling and Cohesion Internal/external method calls null objects Chaining method calls Class constants Class variables.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
1 CSC 222: Object-Oriented Programming Spring 2013 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
1 CSC 221: Computer Programming I Fall 2004 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
COS 260 DAY 5 Tony Gauvin.
Understanding class definitions
1 COS 260 DAY 3 Tony Gauvin. 2 Agenda Questions? 1 st Mini quiz on chap1 terms and concepts –Today In BlackBoard –30 min., M/C and short answer, open.
Chapter 3 Object Interaction.  To construct interesting applications it is not enough to build individual objects  Objects must be combined so they.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Copyright by Scott GrissomCh 2 Class Definition Slide 1 Class Structure public class BankAccount{ fields constructor(s) methods } Sample Code Ticket Machine.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Looking inside classes Conditional Statements Week 4.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Lecture 3: More on Classes Textbook: Chapter 2 Recap: –Classes vs. Objects –Q: What comes first a class or an object? –Q: Do we need a class to create.
Object-Oriented Programming in Java. 2 CS2336: Object-Oriented Programming in Java Buzzwords interfacejavadoc encapsulation coupling cohesion polymorphic.
Understanding class definitions Exploring source code 6.0.
SOFTWARE AND PROGRAMMING 1 Advert : NO TEST1 on 7/02: TEST1 will be 14/02 Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained.
SOFTWARE AND PROGRAMMING 1
CSC 222: Object-Oriented Programming Fall 2015
Class definitions CITS1001 week 2.
Objects First with Java Creating cooperating objects
Java Programming: Guided Learning with Early Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Object INTERACTION CITS1001 week 3.
Understanding class definitions
public class BankAccount{
Java Programming with BlueJ
Understanding class definitions
COS 260 DAY 6 Tony Gauvin.
COS 260 DAY 3 Tony Gauvin.
2 The anatomy of class definitions
Creating cooperating objects
Understanding class definitions
F II 3. Classes and Objects Objectives
Creating cooperating objects
Objects First with Java Creating cooperating objects
COS 260 DAY 4 Tony Gauvin.
Objects First with Java Creating cooperating objects
Defining Classes and Methods
Classes CS 21a: Introduction to Computing I
COS 260 DAY 6 Tony Gauvin.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2

Recap From Previous Session Classes Represent all objects of a kind (example: “a car”) Objects Represent specific items from the real world, or from some problem domain (example: “the red car out there in the parking lot”) An object is an instance of a class – arbitrarily instances can be created Attributes Objects are described by attributes stored in fields Methods Objects have “operations” which can be invoked Parameters Methods may have parameters to pass additional information needed to execute Return values Methods may return values as a result of the operation 2

Programming Style Class names are singular nouns starting with a capital letter Student, LabClass Method and variable names start with lower-case letters makeVisible, calculateVAT 3

Ticket Machine – Inside Perspective Interaction with an object provides clues about it’s behaviour. Looking inside allows us to determine how that behaviour is provided or implemented. All Java classes have a similar-looking internal view. 4

Basic Class Structure 5 public class TicketMachine { Inner part of the class omitted. } public class ClassName { Fields Constructors Methods } The outer wrapper of TicketMachine The contents of a class

Fields Fields store values for an object They are also known as instance variables Use the Inspect option to view an object’s fields Fields define the state of an object 6 public class TicketMachine { private int price; private int balance; private int total; //Constructor and methods omitted. } private int price; visibility modifiertypevariable name

Constructors Constructors initialize an object They have the same name as their class They store initial values into the fields They often receive external parameter values for this 7 public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; }

Passing Data Through Parameters 8

Assignment Values are stored into fields (and other variables) via assignment statements: = ; Example: price = ticketCost; A variable stores a single value, so any previous value is lost. 9

Accessor Methods (get()) Methods implement the behaviour of objects Accessors provide information about an object Methods have a structure consisting of a header and a body The header defines the method’s “signature” public int getPrice() The body encloses the method’s statements 10 public int getPrice() { return price; } return type method name parameter list (empty) start and end of method body (block) return statement visibility modifier

Mutator Methods (set()) Have a similar method structure: header and body Used to “mutate” (i.e., change) an object’s state Achieved through changing the value of one or more fields Typically contain assignment statements Typically receive parameters 11 public void insertMoney(int amount) { balance += amount; } return type ( void ) method name parameter visibility modifier assignment statement field being changed

Printing From Methods 12 public void printTicket() { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the balance. total = total + balance; // Clear the balance. balance = 0; }

Reflecting on the Ticket Machines Their behaviour is inadequate in several ways No checks on the amounts entered No refunds No checks for a sensible initialization How can we do better? We need more sophisticated behaviour 13

Decisions 14 public void insertMoney(int amount) { if(amount > 0) { balance += amount; } else { System.out.println("Use a positive amount: " + amount); }

Decisions 15 if(perform some test) { Do the statements here if the test gave a true result } else { Do the statements here if the test gave a false result } ‘if’ keyword boolean condition to be tested - gives a true or false result actions if condition is true actions if condition is false ‘else’ keyword

16 If-sætning if (count == 0){ System.out.println(”No, value were entered.”); } else { double average = sum/count; System.out.println(”The average is ” + average); }

17 If sætning i if sætning if (height <= 20){ System.out.println(”Situation Normal”); } else{ System.out.println(”Bravo!”); } if (code = = ’R’){ It may be better to make a method if you get to many nested if

Variable Types 18 public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } A local variable No visibility modifier Instance variables (also called object attributes and fields) Describes the attribute of an object, and is accessible throughout the class Same scope as the object (value is stored as long as the object lives) Local variables Used temporarily within the method of a class, and is thus only accessible within the given method.

Data Types 19 A data type is characterized by A set of values (which the data type accepts) Data representation (how are the values stored) A set of operations (the operations to be applied on the data type) Two main categories exist Primitive types (int, long, boolean, char etc.) Object types (strings, references etc.)

Summary Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors initialize objects. Methods implement the behaviour of objects. Fields, parameters and local variables are all variables. Fields persist for the lifetime of an object. Parameters are used to receive values into a constructor or method. Local variables are used for short-lived temporary storage. Objects can make decisions via conditional (if) statements. A true or false test allows one of two alternative courses of actions to be taken. 20

Exercises Blue J Native Ticket Machine: Solve exercise: Constructor 2.21 – 2.27 methods test 2.29 – 2.30, 2.32 new methods for the class 2.33 – 2.38 Print method 2.39 – 2.42 improvements 21

Abstraction and Modularization Abstraction is the ability to ignore details of parts to focus attention on a higher level of a problem Modularization is the process of dividing a whole into well-defined parts, which can be built and examined separately, and which interact in well-defined ways 22

Abstraction 23 Reality ??? Models Tecnology: Hardware, O/S, network, server, etc.. Software Solutions Abstraction Implementation

Modularizing the Digital Clock 24 One four-digit display? Or two two-digit displays?

Implementing the Digital Clock 25 NumberDisplay: public class NumberDisplay { private int limit; private int value; // constructors and // methods omitted } ClockDisplay: public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; // constructors and // methods omitted }

Class Diagram of the Digital Clock 26 Static view

Object Diagram of the Digital Clock 27 Dynamic view

Primitive Types vs. Object Types SomeObject a; int a; Object type Primitive type

Primitive Types vs. Object Types SomeObject a; int a; SomeObject b; b = a; int b; 32

Implementing the NumberDisplay public NumberDisplay(int rollOverLimit) { limit = rollOverLimit; value = 0; } public void increment() { value = (value + 1) % limit; } 30 ‘Modulo' operator – refer to next slide

The Modulo Operator The 'division' operator (/), when applied to int operands, returns the result of an integer division. The 'modulo' operator (%) returns the remainder of an integer division. Generally: 17 / 5 = result 3, remainder 2 In Java: 17 / 5 = 3 17 % 5 = 2 What is the result of: 8 % 3 What are all possible results of: n % 5

Implementing the NumberDisplay public String getDisplayValue() { if(value < 10) return "0" + value; else return "" + value; } 32

Objects Creating Objects public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; private String displayString; public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); } 33

Object Interaction public void timeTick() { minutes.increment(); if(minutes.getValue() == 0) { // it just rolled over! hours.increment(); } updateDisplay(); } private void updateDisplay() { displayString = hours.getDisplayValue() + ":" + minutes.getDisplayValue(); } 34

Object Diagram of the Digital Clock 35

The Parameter - Terminology public NumberDisplay(int rollOverLimit) { limit = rollOverLimit; value = 0; } public class ClockDisplay { public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); } } 36 Formal parameter Actual parameter

Method Calls Internal method calls ( parameter-list ) External method calls. ( parameter-list ) Examples public ClockDisplay() { updateDisplay(); … public void timeTick() { minutes.increment(); … 37 Internal method call External method call

A New Pattern – Class Association 38 AB public class A {……… private B myB; public A{ myB = new B(); } …………….. } public class B { private …… public B() { } ……… }

Summary Abstraction Modularization Class diagram (static) Object diagram (dynamic) Primitive types Object types Object creation Internal/external method call 39

Exercises 3.5, 3.6, 3.7, 3.8 Clock-display 3.13, 3.14 –3.25 Clock-display (3.15 – 3.19 are not exercises to the clock-display) BankExercise01 BankExercise02 CarExercise 40

Another example Customer Number Name Address phone Order Number Date DeliveryDate payDate status Product Id Description Price Stock PartOrder amount

public class Customer { // instance variables private int number; private String address; private String phone; private Order myOrder;//at the moment only one instance of order /** * Constructor for objects of class Customer */ public Customer(int newNr, String newAddress, String newPhone) { number = newNr; address = newAddress; phone = newPhone; } public void setOrder(Order newOrder) { myOrder = newOrder; }

public class Order { // instance variables private int number; private String orderDate; private String delivery; private String payDate; private boolean status; private PartOrder myPartOrder;// at the moment only one partorder pr. order public Order(int newNr, String dato, String newDelivery) { number = newNr; orderDate = dato; delivery = newDelivery; status = false; } public void setPartOrder(PartOrder newPart) { myPartOrder = newPart; }

public class PartOrder { // instance variables - replace the example below with your own private int amount; private Order order;//is connected to one order private Product product;// is connected to one product /** * Constructor for objects of class PartOrder */ public PartOrder(int newAmount, Order newOrder, Product newProduct) { amount = newAmount; order = newOrder; product = newProduct; }

public class Product { // instance variables private int id; private String description; private double price; private int amountOnStock; /** * Constructor for objects of class Product */ public Product(int newId, String newDescription, double newPrice, int newStock) { id = newId; description = newDescription; price = newPrice; amountOnStock = newStock; } }

Exercise Customer – Order –Part Print out information about an order