Java and OOP. Part 2 Classes and objects

Similar documents
Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Chapter 4 Defining Classes I

Principles of Object Oriented Programming. Lecture 4

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Objects as a programming concept

Chapter 4. Defining Classes I

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Object Oriented Programming in C#

Object Oriented Programming

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

University of Palestine. Mid Exam Total Grade: 100

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Lecture 3. Lecture

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

Introduction to Java. Handout-1d. cs402 - Spring

Classes Classes 2 / 36

BM214E Object Oriented Programming Lecture 8

Java Foundations. 7-2 Instantiating Objects. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

CS 302 Week 9. Jim Williams

Computer Science II (20073) Week 1: Review and Inheritance

Chapter 6 Lab Classes and Objects

Object Oriented Programming

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Classes. Classes as Code Libraries. Classes as Data Structures

Text User Interfaces. Keyboard IO plus

Object-Oriented Programming Concepts

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

OpenStax-CNX module: m Java3002r Review * R.G. (Dick) Baldwin

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Programming Exercise 14: Inheritance and Polymorphism

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Building Java Programs

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

*Java has included a feature that simplifies the creation of

Handout 7. Defining Classes part 1. Instance variables and instance methods.

1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 4, 2005

Java Identifiers, Data Types & Variables

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

Building Java Programs

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Methods. Methods. Mysteries Revealed

STUDENT LESSON A5 Designing and Using Classes

Introduction to Programming Using Java (98-388)

9 Working with the Java Class Library

Design Patterns: State, Bridge, Visitor

Building Java Programs

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

Classes Classes 2 / 35

Methods and Data (Savitch, Chapter 5)

CSC-140 Assignment 6

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

JAVA: A Primer. By: Amrita Rajagopal

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Selected Questions from by Nageshwara Rao

APCS Semester #1 Final Exam Practice Problems

CS 231 Data Structures and Algorithms, Fall 2016

Lecture 5: Methods CS2301

MIDTERM REVIEW. midterminformation.htm

Chapter 6 Lab Classes and Objects

Software and Programming 1

Chapter 12: How to Create and Use Classes

Chapter 11: Create Your Own Objects

The Essence of OOP using Java, Nested Top-Level Classes. Preface

User-built data types Mutable and immutable data

Options for User Input

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Lecture Set 4: More About Methods and More About Operators

Lecture 02, Fall 2018 Friday September 7

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 15: Object Oriented Programming

AP Computer Science Unit 1. Programs

Assignment 1 due Monday at 11:59pm

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The Java language has a wide variety of modifiers, including the following:

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Class, Variable, Constructor, Object, Method Questions

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

What will this print?

Object-Oriented Programming in Java

Chapter 5: Classes and Objects in Depth. Information Hiding

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Object-Oriented Programming Concepts

CHAPTER 7 OBJECTS AND CLASSES

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Modeling

In Java there are three types of data values:

Lecture 7: Classes and Objects CS2301

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Notes on Chapter Three

Transcription:

Java and OOP Part 2 Classes and objects 1

Objects OOP programs make and use objects An object has data members (fields) An object has methods The program can tell an object to execute some of its methods 2

Classes A class is a definition or type for an object Objects belong to classes An object instantiates a class Classes can have several objects - instances A class is defined in a source code file with the same name as the class 3

public class Product public int barcode; public int stocklevel; The Product Class Models a stock control item 2 data members, barcode and stocklevel Defined in file name Product.java Compiled to Product.class Cannot run it no main method 4

Using the Product class public class First public static void main(string[] args) Product p1 = new Product(); p1.barcode=3; p1.stocklevel=20; Product p2 = new Product(); p2.barcode=4; p2.stocklevel=60; Classes start with capital letters Everything else does not This instantiates 2 Product objects ( new ) and sets their data members This can be run but no output 5

public class Product Adding a display method public void display() System.out.println("Barcode = "+barcode); System.out.println("Stocklevel = "+stocklevel); System.out.println("========================="); public int barcode; public int stocklevel; Check out how the display method is defined barcode means the barcode field of the object executing this method NB barcode is not a variable 6

public class First public static void main(string[] args) Product p1 = new Product(); p1.barcode=3; We tell products p1 and p2 to do p1.stocklevel=20; p1.display(); their display methods. Product p2 = new Product(); Run this code out p2.barcode=4; p2.stocklevel=60; p2.display(); Using the display method 7

Constructors A constructor is something which 'makes' an object A class will nearly always have a constructor defined A constructor can have parameters, usually used to give initial values to fields. 8

public class Product public Product(int initbarcode, int initstocklevel) barcode=initbarcode; stocklevel=initstocklevel; Product constructor check how a constructor is named public void display() System.out.println("Barcode = "+barcode); System.out.println("Stocklevel = "+stocklevel); System.out.println("========================="); public int barcode; public int stocklevel; 9

Using the constructor public class First public static void main(string[] args) Product p1 = new Product(3,20); p1.display(); Product p2 = new Product(4,60); p2.display(); new invokes constructor Check how initial values are passed in the constructor 10

Methods which take parameters public class Product..previous code omitted parameter public void deliver(int howmany) stocklevel+=howmany; public int barcode; public int stocklevel; 11

Product p1 = new Product(3,20); p1.deliver(10); p1.display(); Product p2 = new Product(4,60); p2.deliver(20); p2.display(); Using the deliver method 12

Exercise Copy the Product class (constructor, display and deliver methods) Add a sell method. This takes a parameter of how many to sell, and it reduces the stock level. If it is told to sell more than it has, the stock level should become 0. Check it works 13

methods which return values public boolean needmore() if (stocklevel==0) return true; else return false; This is a method of the Product class See how the return type (boolean) is included, like a C function return type 14

Product p1 = new Product(3,20); p1.deliver(10); p1.sell(40); if (p1.needmore()) p1.deliver(50); p1.display(); Using the new method 15

Encapsulation Central to the philosophy of OOP Means data in objects are 'closed up' Other parts of the application cannot accidentally alter data within an object Increases modularity When you use a class, no need to worry about messing it up. How to do it.. 16

Encapsulation.. private int barcode; private int stocklevel;.. This is part of the definition of the class Product Data members should be declared private not public Rest of code runs unaltered, but.. 17

Attempt to access private member from another class: Product p1 = new Product(3,20); p1.deliver(10); p1.sell(40); if (p1.needmore()) p1.deliver(50); p1.display(); p1.stocklevel=22; C:\Walter\java\javaprogs\First.java:11: stocklevel has private access in Product p1.stocklevel=22; ^ 1 error 18

public void deliver(int howmany) if (howmany<0) System.out.println("Invalid delivery"); return; else stocklevel+=howmany; Product p1 = new Product(3,20); p1.deliver(-10); p1.display(); Validating access Methods which alter data members should validate the change Here the deliver method of Product checks for ve quantity delivered 19

Accessor methods Data members should usually be private But often we want to find out the values of those members from outside the class Or to change them Solution public accessor methods Method to 'read' a data member XXX usually called 'getxxx' Methods to 'write' to a data member XXX called 'setxxx' Set methods must validate the change they are making 20

.. public int getstocklevel() return stocklevel;.. private int stocklevel; Typical get method: Product p1 = new Product(3,20); int x = p1.getstocklevel(); System.out.println(x); using it 21

Overloading You can have different versions of the same method with the same name This is called overloading Different versions must have different numbers or types of arguments For example.. 22

public void deliver() stocklevel+=100; public void deliver(int howmany) if (howmany<0) System.out.println("Invalid delivery"); return; else stocklevel+=howmany; Overloading example One version delivers a default 100 units Second version allows specifying the delivery quantity 23

Constructor overloading Constructors are usually overloaded Such as.. 24

Constructor overloading public Product(int initbarcode, int initstocklevel) barcode=initbarcode; One defaults to an initial stocklevel=initstocklevel; stock level of 100 public Product(int initbarcode) Other allows to specify it In use.. barcode=initbarcode; stocklevel=100; Product p1 = new Product(3,20); p1.display(); Product p2=new Product(4); p2.display(); 25

Default no-arg constructors The constructor with no arguments is called 'the no-args constructor' Like Product p = new Product(); If you do not define any constructors, then.. the system calls a default version for you If you do define some (with args), and you call Product p = new Product(); then You must explicitly define the no-arg version 26

Static variables A static or class variable is a piece of data for the whole class, not for individual objects For example, we need to ensure product barcodes are unique. One way is to 'autonumber' them This means the Product class must remember the last one used.. 27

Using a static field.. public Product() lastbarcodeused++; barcode=lastbarcodeused; stocklevel=100;.. private static int lastbarcodeused=0; private int barcode; private int stocklevel;.. Revised constructor barcode and stocklevel have different values for each Product object There is a single lastbarcodeused value for the class 28

Using the revised constructor Product p1 = new Product(); Product p2=new Product(); Product p3=new Product(); p1.display(); p2.display(); p3.display(); 29

Static methods // a static method to the Product class public static int count() return lastbarcodeused; // use it.. Product p1 = new Product(); Product p2=new Product(); Product p3=new Product(); System.out.println("There are now "+Product.count()+" products"); 30

public static void main() This is a method It does not return a value (void) It is static (just one of it- don't need to construct an object) It is public (so we can call it) It is special in that execution starts there as for C 31

Review Review the product class definition we have: 32

Product class definition public class Product What are these called? private static int lastbarcodeused=0; private int barcode; private int stocklevel; Why are these private? public Product() lastbarcodeused++; barcode=lastbarcodeused; stocklevel=100; public Product(int initstock) lastbarcodeused++; barcode=lastbarcodeused; stocklevel=initstock; What is this? Two things same name called what? 33

More Product Why is this static? public static int count() return lastbarcodeused; Why is this int? public void display() System.out.println("Barcode = "+barcode); System.out.println("Stocklevel = "+stocklevel); System.out.println("========================="); Why is this void? 34

Rest of Product public void deliver(int howmany) Why do this? if (howmany<0) When do we use getxxx? System.out.println("Invalid delivery"); What are these methods return; called? else stocklevel+=howmany; public int getstocklevel() return stocklevel; 35

Arrays of objects To have an array of objects there are 2 steps: 1. make the array 2. make the objects to put in the array 36

Arrays of objects // declare the type of stock.. Product stock[]; // call the array constructor to make the array.. stock = new Product[10]; // make 10 objects and put them in the array: for (int i=0; i<10; i++) stock[i]=new Product(); // show they exist: for (int i=0; i<10; i++) stock[i].display(); 37