More on Objects and Classes



Similar documents
Introduction to Programming

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Part I. Multiple Choice Questions (2 points each):

AP Computer Science Static Methods, Strings, User Input

Introduction to Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Object-Oriented Programming in Java

Chapter 2 Introduction to Java programming

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Building Java Programs

Comp 248 Introduction to Programming

Java Classes. GEEN163 Introduction to Computer Programming

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Install Java Development Kit (JDK) 1.8

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Basics of Java Programming Input and the Scanner class

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

AP Computer Science Java Subset

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Week 1: Review of Java Programming Basics

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Building Java Programs

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

6.1. Example: A Tip Calculator 6-1

Java Interview Questions and Answers

JAVA ARRAY EXAMPLE PDF

java Features Version April 19, 2013 by Thorsten Kracht

Crash Course in Java

Topic 11 Scanner object, conditional execution

Java CPD (I) Frans Coenen Department of Computer Science

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Data Structures Lecture 1

Sample CSE8A midterm Multiple Choice (circle one)

D06 PROGRAMMING with JAVA

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Introduction to Object-Oriented Programming

Basic Object-Oriented Programming in Java

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Building Java Programs

Object Oriented Software Design

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

An Overview of Java. overview-1

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

LAB4 Making Classes and Objects

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Lecture 5: Java Fundamentals III

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 1 Java Program Design and Development

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Introduction to Java Lecture Notes. Ryan Dougherty

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Chapter 3. Input and output. 3.1 The System class

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

Java: overview by example

CSC 551: Web Programming. Fall 2001

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Introduction to Java. CS 3: Computer Programming in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object-Oriented Programming Lecture 2: Classes and Objects

Programming Language Concepts: Lecture Notes

Inheritance, overloading and overriding

Software Development in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

C++ INTERVIEW QUESTIONS

Moving from CS 61A Scheme to CS 61B Java

CS506 Web Design and Development Solved Online Quiz No. 01

Object Oriented Software Design

1001ICT Introduction To Programming Lecture Notes

Problem Solving. Software Engineering. Behavior. OCD in a Nutshell. Behavior. Objects Operations Algorithm. Object-Centered Design

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CS 106 Introduction to Computer Science I

Building Java Programs

Some Scanner Class Methods

CS 111 Classes I 1. Software Organization View to this point:

Java Crash Course Part I

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CSE 8B Midterm Fall 2015

How to Install Java onto your system

Chapter 2: Elements of Java

public void creditaccount(string accountnumber, float amount) { this.accounts.get(accountnumber).credit(amount); }

Programmierpraktikum

Java Programming Fundamentals

Chapter 2 Elementary Programming

CS170 Lab 11 Abstract Data Types & Objects

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Computer Programming I

Transcription:

Software and Programming I More on Objects and Classes Roman Kontchakov Birkbeck, University of London

Outline Object References Class Variables and Methods Packages Testing a Class Discovering Classes Sections 7.6 7.10 slides are available at www.dcs.bbk.ac.uk/ roman/sp1 SP1 2013-06 1

Java Compilation source compiler CashRegister.java javac source CashRegisterTest.java bytecode CashRegister.class bytecode CashRegisterTest.class Virtual Machine java public static void main(string[] args) {... } NB: statements must be inside methods! running program SP1 2013-06 2

Object-Oriented Programming Tasks are solved by collaborating objects Each object has its own set of encapsulated data, together with a set of methods that act upon the data (public interface) A class describes a set of objects with the same structure (i.e., data) and behaviour (i.e., methods) Encapsulation enables changes in the implementation without affecting users of the class all instances variables should be private most methods should be public SP1 2013-06 3

Example: Cash Register 1 class CashRegister { 2 /* private data (instance variables) */ 3 private int itemcount; 4 private double totalprice; 5 /* methods (public interface) */ 6 public void additem(double price) 7 { itemcount++; totalprice += price; } 8 public void clear() 9 { itemcount = 0; totalprice = 0; } 10 public double gettotal() { return totalprice; } 11 public int getcount() { return itemcount; } 12 } additem(double) and clear() are mutators; gettotal() and getcount() are accessors SP1 2013-06 4

Using the CashRegister 1 // constructing objects 2 CashRegister reg1 = new CashRegister(); 3 CashRegister reg2 = new CashRegister(); 4 // invoking methods 5 reg1.additem(1.95); 6 reg1.additem(2.99); 7 System.out.println(reg1.getTotal() + " " + 8 reg1.getcount()); 9 reg2.additem(7.67); 10 System.out.println(reg2.getTotal() + " " + 11 reg2.getcount()); 12 reg1.itemcount = 0; // ERROR: private variable SP1 2013-06 5

Instance Variables reg1 reg2 Every instance of a class has its own set of instance variables CashRegister itemcount = 2 totalprice = 4.94 CashRegister itemcount = 1 totalprice = 7.67 An object reference specifies the location of an object SP1 2013-06 6

Primitive Datatypes: Values are Copied 1 int num1 = 0; num1 0 2 int num2 = num1; num1 0 num2 0 3 num2++; num1 0 num2 by executing num2++; only num2 is changed, num1 remains the same SP1 2013-06 7 1

Objects: References are Copied 1 CashRegister reg1 = new CashRegister(); reg1 2 CashRegister reg2 = reg1; reg1 reg2 CashRegister itemcount = 0 totalprice = 0 CashRegister itemcount = 0 totalprice = 0 3 reg2.additem(2.95); reg1 CashRegister reg1 and reg2 refer to the same object itemcount = 1 and so, all modifications by methods on reg2 reg2 totalprice = 2.95 are reflected in reg1 SP1 2013-06 8

The null Reference The null reference refers to no object 1 String middleinitial = null; // not the same as ""! 2 if (middleinitial == null) 3 System.out.println(firstName + " " + lastname); 4 else 5 System.out.println(firstName + " " + 6 middleinitial + " " + lastname); It is an error to invoke a method on a null reference: 1 CashRegister reg1 = null; 2 // ERROR: null pointer exception 3 System.out.println(reg1.getTotal()); SP1 2013-06 9

The this reference In a method (or constructor) this refers to the object the method is called on 1 public void additem(double price) { 2 this.itemcount++; // matter of taste 3 this.totalprice += price; 4 } 5 public CashRegister() { 6 this.clear(); // or simply clear(); 7 } NB: we shall see substantial uses of this later SP1 2013-06 10

Class Variables A static variable belongs to the class, not to any object of the class 1 public class BankAccount { 2 private double balance; // instance variable 3 private int accountnumber; // instance variable 4 // class variable 5 private static int lastassignednumber = 1000; 6 7 public BankAccount() { 8 lastassignednumber++; // one for all instances 9 accountnumber = lastassignednumber; 10 } 11 } SP1 2013-06 11

Class Constants 1 public class BankAccount { 2 public static final double OVERDRAFT_FEE = 29.95; 3 } methods from any class can refer to this constant as BankAccount.OVERDRAFT FEE NB: other examples include Math.PI: public static final double PI System.out: public static final PrintStream out javax.xml.xmlconstants.xmlns ATTRIBUTE: public static final String XMLNS ATTRIBUTE... SP1 2013-06 12

Class Methods 1 public class Financial { 2 public static double percentof(double percentage, 3 double amount) { 4 return (percentage / 100) * amount; 5 } 6 } class methods are not invoked on an object: System.out.println(Financial.percentOf(50, 100)); NB: other examples include Math.abs, Math.sqrt,... NB: can one use this in a class method? SP1 2013-06 13

Packages a package is a set of related classes, e.g., java.util the import directive lets you refer to a class from a package by its class name, without the package prefix 1 import java.util.scanner; // before classes 2... 3 Scanner = new Scanner(System.in); 4... without this directive one must use the full class name to import all classes of the package java.util, use import java.util.* SP1 2013-06 14

Packages to put a class in a package, use package packagename; as the first statement in the source file use a domain name in reverse to construct an unambiguous package name: e.g., uk.ac.bbk.dcs.sp1 the path of a class file must match its package name: e.g., uk.ac.bbk.dcs.sp1 is looked up at uk/ac/bbk/dcs/sp1 in the CLASSPATH directories SP1 2013-06 15

Overloading Methods and constructors can have the same name (provided their signature (i.e., name and types of parameters) are different) 1 public class CashRegister { 2 //... 3 public CashRegister() { 4 itemcount = 0; 5 totalprice = 0; 6 } 7 public CashRegister(CashRegister c) { 8 this.itemcount = c.itemcount; 9 this.totalprice = c.totalprice; 10 } 11 } SP1 2013-06 16

Overloading (2) 1 // constructor 1: CashRegister() 2 CashRegister reg1 = new CashRegister(); 3 reg1.additem(2.95); CashRegister reg1 4 // constructor 2: CashRegister(CashRegister) 5 CashRegister reg2 = new CashRegister(reg1); reg2 itemcount = 1 totalprice = 2.95 CashRegister itemcount = 1 totalprice = 2.95 NB: type of arguments determines which constructor is called SP1 2013-06 17

Testing a Class 1 public class CashRegisterTester { 2 public static void main(string[] args) { 3 CashRegister reg1 = new CashRegister(); 4 reg1.additem(2.95); 5 reg1.additem(1.99); 6 System.out.println(reg1.getCount()); 7 System.out.println((reg1.getCount() == 2) 8? "OK" : "FAIL"); 9 System.out.printf("%.2f\n", reg1.gettotal()); 10 System.out.println((reg1.getTotal() == 4.94) 11 12 } 13 }? "OK" : "FAIL"); SP1 2013-06 18

Discovering Classes Find the concepts that you need to implement as classes. Often these will be nouns in the problem description Find the responsibilities of the classes. Often these will be verbs in the problem description. Find relationships between the classes that you have discovered (aggregation, inheritance) Class-Responsibility-Collaboration cards subject of OO Analysis and Design SP1 2013-06 19

Take Home Messages encapsulation enables changes in implementation all instances variables should be private most methods should be public (public interface) every instance of a class has its own instance variables assignment statements copy values for primitive datatypes object references for object the null reference refers to no object static variables and methods belong to the class a package is a set of related classes SP1 2013-06 20