CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

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

Introduction to Object-Oriented Programming

Java Interview Questions and Answers

Java Classes. GEEN163 Introduction to Computer Programming

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

More on Objects and Classes

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

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

C++ INTERVIEW QUESTIONS

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

Install Java Development Kit (JDK) 1.8

Inheritance, overloading and overriding

Basic Object-Oriented Programming in Java

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

JAVA - OBJECT & CLASSES

History OOP languages Year Language 1967 Simula Smalltalk

Java CPD (I) Frans Coenen Department of Computer Science

Object Oriented Software Design II

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

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

An Introduction To UML Class Diagrams Classes

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Description of Class Mutation Mutation Operators for Java

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Introduction to Java. CS 3: Computer Programming in Java

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Object-Oriented Programming in Java

public static void main(string[] args) { System.out.println("hello, world"); } }

Chapter 13 - Inheritance

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

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

Konzepte objektorientierter Programmierung

Java: overview by example

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Object-Oriented Programming in Java

LAB4 Making Classes and Objects

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Computer Programming C++ Classes and Objects 15 th Lecture

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

CS170 Lab 11 Abstract Data Types & Objects

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

Classes: Relationships Among Objects. Atul Prakash Background readings: Chapters 8-11 (Downey)

Contents. 9-1 Copyright (c) N. Afshartous

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

Lecture J - Exceptions

Object-Oriented Programming Lecture 2: Classes and Objects

Design Patterns in Java

Manual For Using the NetBeans IDE

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Note: Syntactically, a ; is needed at the end of a struct definition.

Java Programming Language

1 Posix API vs Windows API

PHP Object Oriented Classes and objects

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

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

Lecture 5: Java Fundamentals III

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

CMSC 202H. ArrayList, Multidimensional Arrays

WRITING DATA TO A BINARY FILE

AP Computer Science Java Subset

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Stack Allocation. Run-Time Data Structures. Static Structures

Conversion Constructors

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

java Features Version April 19, 2013 by Thorsten Kracht

Java Basics: Data Types, Variables, and Loops

Threads 1. When writing games you need to do more than one thing at once.

STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS

The Interface Concept

Building Java Programs

Moving from CS 61A Scheme to CS 61B Java

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

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

If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket.

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

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Android Studio Application Development

Object Oriented Software Design

Introduction to Object-Oriented Programming

Kotlin for Android Developers (Preview)

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Crash Course in Java

Introduction to Java

13 Classes & Objects with Constructors/Destructors

Week 2 Practical Objects and Turtles

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Abstract Class & Java Interface

Transcription:

This Week CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 School of Computer Science University of St Andrews Graham Kirby Alan Dearle More on Java classes Constructors Modifiers cdn.videogum.com/img/thumbnails/photos/commenter.jpg http://www.rodgersleask.co.uk/images/sc2.jpg 2 Fields and Variables W05 Example 1: Variables & Fields 1 A field: ú has a type and identifier ú holds information relevant to object of specific class ú is defined in class ú exists as long as the object does A variable: ú has a type and identifier ú holds temporary information relevant to method execution ú is defined in method ú exists only while method is being executed private int a = 2; public void m() { int b = 7; b = 16; a = -9; field declaration variable declaration variable update field update obj.m(); object creation method call 3 University of St Andrews 2011/12 CS1002 Computer Science - OO Modelling & Design - Week 5 4 1

Memory States private int a = 2; public void m() { int b = 7; b = 16; a = -9; obj.m(); W05 Example 2: Variable Scope public void m1() { int i = 32; System.out.println("i: " + i); public void m2() { i = i - 3; variable i is created here...... and disappears again here this is illegal: i is out of scope 2 5 University of St Andrews 2011/12 CS1002 Computer Science - OO Modelling & Design - Week 5 6 W05 Example 3: Method Calls public void m1() { C another_one = new C(); another_one.m2(); this.m2(); m2(); public void m2() {... method call on a different object method calls on this object obj.m1(); 3 Memory States public void m1() { C another_one = new C(); another_one.m2(); this.m2(); m2(); public void m2() {... public static void main(string[] args) { obj.m1(); University of St Andrews 2011/12 CS1002 Computer Science - OO Modelling & Design - Week 5 7 8 2

Method Parameters www.coolingtower- profiler.com/robo_kran.jpg 4 Methods take parameters: ú information passed to the method when it's called, to tell it specifically what to do ú each parameter is treated like a variable within the method body equivalent to a variable containing the value specified by the caller of the method W05 EXAMPLE 4: METHOD PARAMETERS 9 Parameter and Field Names 5 Distinguishing Parameters and Fields 6 Sometimes convenient to use fields and parameters with the same names: int salary = 0; public void setsalary(int salary) { salary = salary; the parameter the parameter obj.setsalary(400); Doesn t do what you want the field System.out.println("obj.salary = " + obj.salary); 11 int salary = 0; public void setsalary(int salary) { this.salary = salary; the parameter value the field the field obj.setsalary(400); System.out.println("obj.salary = " + obj.salary); 12 3

Constructors We may wish to ensure that new objects of a particular class are always initialised in a certain way Student s = new Student(); Constructors cont'd A constructor is like a special method that is executed when an object is created ú can initialise the object in any required way ú can take parameters, like method ú doesn't return any result ú always has the same name as the class supercolossal.ch/blog/skynet_high%20speed%20constructor.png 13 14 W05 Example 7: Single Constructor 7 Test Class public Student(String name, String id) { this.name = name; this.id = id; year = 2004; Can put code in Test class to test other class implementation e.g. ú instantiate student object with name and id ú print out the details of the student object public class Test { Can now create student object with Student s = new Student("Jane Jones", "040412716"); Student s = new Student("Jane", "040412716"); s.printdetails(); 15 16 4

Multiple Constructors 8 May want several different ways to initialise objects ú can have more than one constructor in a class ú but they must all take different parameters why? Use Student s1 = new Student("Jane Jones", 040412716"); Student s2 = new Student(); Student s3 = new Student("Jane Jones"); Example of overloading ú the identifier of the constructor refers to different bits of code depending on the number and type of its arguments www.activoinc.com/blog/wp- content/uploads/2009/06/overload_cargo.jpg W05 EXAMPLE 8: MULTIPLE CONSTRUCTORS 17 Default Constructor Simple constructor defined automatically if we don t write any ú just creates instance and fills in default attribute values ú equivalent to, for : public Student() { this.name = null; this.id = null; this.year = 0; Linking Constructors So we have seen ú a class can have multiple constructors ú distinguished by different parameters May want to call one constructor from another, to avoid duplicating code ú use this keyword 19 20 5

9 Method Overloading 10 We have seen multiple constructors with the same names but different parameters W05 EXAMPLE 9: LINKED CONSTRUCTORS ú can also do the same with other methods ú only do this when the methods are closely related in purpose... 22 Encapsulation Encapsulated Objects An object s field values are (should be) encapsulated ú they can t be seen directly by other objects ú but can be accessed by that object s methods Alan Dearle Benefits ú improves control over how field values are read and updated ú helpful in structuring software can change one part without affecting others Graham Kirby 23 24 6

Getters and Setters 11 Visibility and Other Modifiers So, may need to write methods for each class that allow other objects to access its fields Accessor methods: ú set the content of a field to a certain value (setter) ú return the value held in a field (getter) Provides standardised access to fields by ú other parts of your program (other classes) ú other programmers when using your code Some modifiers: ú public, private, protected, static, final Apply to classes and other members: ú fields, methods, constructors www.arteworks.biz/phamilton/uploaded_images/long- tail- modifiers- 774652.jpg 25 26 public Modifier private Modifier Modifier for classes, fields, methods, constructors ú means that class or member can be accessed from anywhere ú no restrictions: class can be instantiated field can be read or updated method can be called constructor can be called public class Person { public String name; public int getage(){... public Person(String s) {... Modifier for fields, methods, constructors ú means that member can't be accessed from anywhere outside the class ú restrictions: field can't be read or updated method can't be called constructor can't be called public class Person { private String name; private int getage();... private Person(String s);... ú the normal modifier for fields 27 28 7

protected Modifier Modifier for fields, methods, constructors ú means that member can be accessed only from the defining class or another class in the same package static Modifier Modifier for fields and methods ú means that member is associated with class as a whole rather than individual object public class Person { protected String name; protected int getage();... protected Person(String s);... ú the default if you don't write any visibility modifier 29 30 Static Fields Fields can belong to an instance of the class (object) or to all instances (objects) of the class 12 For non- static fields there is a memory slot inside every object of a certain class For static fields there is a single memory slot which pertains to the whole class www.tyhen.com/images/staticfield.jpg W05 EXAMPLE 12: STATIC FIELD Need to decide which is sensible... 31 8

Static Fields cont d Static fields can be referred to from outside a class (subject to visibility) using the class name, e.g. Person.number_of_people Within the class, they can be referred to just like non- static fields i.e. without the class name prefix Static Methods Methods can also be declared static ú already seen this with main method: public static void main(string[] args){ Only makes sense when method doesn t have anything to do with any particular instance of the class, e.g. public static int gettotalpeople(){ return number_of_people; 33 34 Static Methods cont d Static methods can also be referred to from outside a class using the class name, e.g. int count = Person.getTotalPeople(); double x = Math.sin(0.6); String string_rep = String.valueOf(4.251); Rule A static thing can't access a non- static thing code in a static method code initialising a static field a non- static field a non- static method 35 36 9

final Modifier The static keyword is perhaps confusing ú suggests that the value of the field cannot change Use final keyword to declare a field to be constant ú once a value has been assigned to it, it cannot be changed public static final int MAX_ARRAY_SIZE = 100; private static final String PROMPT = "enter int"; final int x = y + z; Modifier applies to methods too ú we'll see later what this means (to do with inheritance) 37 10