Object-Oriented Programming, Part 1

Similar documents
The Interface Concept

Java Interview Questions and Answers

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

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

AP Computer Science Java Subset

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

Introduction to Java

CMSC 202H. ArrayList, Multidimensional Arrays

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

Java from a C perspective. Plan

Moving from CS 61A Scheme to CS 61B Java

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

Introduction to Object-Oriented Programming

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

J a v a Quiz (Unit 3, Test 0 Practice)

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Java Programming Fundamentals

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

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

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

Crash Course in Java

java Features Version April 19, 2013 by Thorsten Kracht

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

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

C++ INTERVIEW QUESTIONS

Class 16: Function Parameters and Polymorphism

Inheritance, overloading and overriding

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Java Programming Language

Semantic Analysis: Types and Type Checking

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Chapter 1 Java Program Design and Development

Chapter 13 - Inheritance

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

Java Classes. GEEN163 Introduction to Computer Programming

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

Programmation 2. Introduction à la programmation Java

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

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

Introduction to Object-Oriented Programming

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Chapter 5 Names, Bindings, Type Checking, and Scopes

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

The C Programming Language course syllabus associate level

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

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

Java Crash Course Part I

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.

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

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

Web development... the server side (of the force)

Description of Class Mutation Mutation Operators for Java

Object Oriented Software Design

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

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

Chapter 2 Introduction to Java programming

LAB4 Making Classes and Objects

CSC 551: Web Programming. Fall 2001

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

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

Computer Programming I

Software Engineering Techniques

13 Classes & Objects with Constructors/Destructors

History OOP languages Year Language 1967 Simula Smalltalk

Java (12 Weeks) Introduction to Java Programming Language

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Java CPD (I) Frans Coenen Department of Computer Science

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

An Incomplete C++ Primer. University of Wyoming MA 5310

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

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Basic Object-Oriented Programming in Java

objectives chapter Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers.

Lecture 5: Java Fundamentals III

D06 PROGRAMMING with JAVA

Tutorial on Writing Modular Programs in Scala

Object-Oriented Programming Lecture 2: Classes and Objects

CS170 Lab 11 Abstract Data Types & Objects

ICOM 4015: Advanced Programming

Habanero Extreme Scale Software Research Project

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:

Glossary of Object Oriented Terms

Stack vs. Heap. Introduction to Programming. How the Stack Works. Primitive vs. Reference Types. Stack

CS 106 Introduction to Computer Science I

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Chapter 3: Restricted Structures Page 1

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

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

Facebook Twitter YouTube Google Plus Website

Pemrograman Dasar. Basic Elements Of Java

Introduction to Java. CS 3: Computer Programming in Java

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

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

Transcription:

Classes Methods Object-Oriented Programming, Part 1 Argument and return value Overloading Object Creation and Destruction Equality OOP: Object-Oriented Programming, Part 1 1

Classes in Java A class encapsulates a set of properties Some properties are hidden The remaining properties are the interface of the class class ClassName { int x, y; datadeclaration Data declarations char c; constructors methods Constructors Methods OOP: Object-Oriented Programming, Part 1 2

Example of a Class public class Coin { // [Source Lewis and Loftus] public static final int HEADS = 0; public static final int TAILS = 1; private int face; public Coin () { // constructor flip(); public void flip (){ // method procedure face = (int) (Math.random() * 2); public int getface (){ // method function return face; public String tostring(){ // method function String facename; if (face == HEADS) facename = "Heads"; else facename = "Tails"; return facename; OOP: Object-Oriented Programming, Part 1 3

Instance Variables An instance variable is a data declaration in a class. Every object instantiated from the class has its own version of the instance variables. class Car { private String make; private String model; private double price; make: Ford model: Taurus price: 100 car1 make: Opel model: Kadett price: 2500 car2 make: BMW Model: M1 price: 100 car3 OOP: Object-Oriented Programming, Part 1 4

Methods in Java A method is a function or procedure that reads and/or modifies the state of the class. A function returns a value (a procedure does not). A procedure has side-effects, e.g., change the state of an object. char calc (int num1, int num2, String message) return type method name Parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument OOP: Object-Oriented Programming, Part 1 5

All methods have a return type void for procedures Methods in Java, cont. A primitive data type or a class for functions The return value Return stop the execution of a method and jumps out Return can be specified with or without an expression Parameter are pass-by-value Class parameter are passed as a reference public double getprice() { return price; public void increasecounter() { counter = counter + 1; //return; public double geterror() { double a = 0; a++; // compile-error OOP: Object-Oriented Programming, Part 1 6

Method in Java, Example public class Car{ // snip /** Calculates the sales price of the car */ public int salesprice(){ return (int)price; /** Calculates the sales price of the car */ public int salesprice(int overhead){ return (int)price + overhead; /** Calculates the sales price of the car */ public double salesprice(double overheadpercent){ return price + (overheadpercent * price); /** Overwrites the tostring method */ public String tostring(){ return "make " + getmake() + " model " + getmodel() + " price " + getprice(); OOP: Object-Oriented Programming, Part 1 7

What is wrong here? Method in Java, Example, cont public class Car{ // snip /** Calculates the integer sales price of the car */ public int salesprice(){ return (int)price; /** Calculates the double sales price of the car */ public double salesprice(){ return (double)price; public static void main(string[] args){ Car vw = new Car( VW, Golf, 1000); vw.salesprice(); OOP: Object-Oriented Programming, Part 1 8

Scope public int myfunction (){ // start scope 1 int x = 34; // x is now available { // start scope 2 int y = 98; // both x and y are available // cannot redefine x here compile-time error // end scope 2 // now only x is available // y is out-of-scope return x; // end scope 1 The redefinition of x in scope 2 is allowed in C/C++ OOP: Object-Oriented Programming, Part 1 9

Object can be created by Object Creation in General Instantiating a class Copying an existing object Instantiating Static: Objects are constructed and destructed at the same time as the surrounding object. Dynamic: Objects are created by executing a specific command. Copying Often called cloning OOP: Object-Oriented Programming, Part 1 10

Object Destruction in General Object can be destructed in two way. Explicit Implicit Explicit, e.g., by calling a special method or operator (C++). Implicit, when the object is no longer needed by the program (Java). An object in use can be destructed. Not handling destruction can cause memory leaks. Objects are destructed automatically by a garbage collector. There is a performance overhead in starting the garbage collector. There is a scheduling problem in when to start the garbage collector. OOP: Object-Oriented Programming, Part 1 11

Object Creation in Java Instantiazion: A process where storage is allocated for an empty object. Initialization: A process where instances variables are assigned a start value. Dynamic instantiazion in Java by calling the new operator. Static instantiazion is not supported in Java. Cloning implemented in Java via the method clone() in class java.lang.object. Initialization is done in constructors in Java Very similar to the way it is done in C++ OOP: Object-Oriented Programming, Part 1 12

Object Destruction in Java Object destruction in Java is implicit an done via a garbage collector. Can be called explicitely via System.gc(). A special method finalize is called immediately before garbage collection. Method in class Object, that can be redefined. Takes no parameters and returns void. Used for releasing resources, e.g., close file handles. Rarely necessary, e.g., dead-conditions for error dection purposes. OOP: Object-Oriented Programming, Part 1 13

Objects and References Variables of non-primitive types that are not initialized have the special value null. Test: var1 == null Assignment: var2 = null Object have identity but no name, i.e., not possible to identify an object O1 by the name of the variable referring to O1. Aliasing: Many variables referring to the same object var1 var2 var3 make: BMW model: M1 engine: ref car3 cylinders: 6 KW: 130 engine1 OOP: Object-Oriented Programming, Part 1 14

Constructors in Java A constructor is a special method where the instance variables of a newly created object are initialized with reasonable start values. A class must have a constructor A default is provided implicitly (no-arg constructor). A constructor must have the same name as the class. A constructor has no return value. That's why it is as special method A constructor can be overloaded. A constructor can call other methods (but not vice-versa). A constructor can call other constructors (via this). OOP: Object-Oriented Programming, Part 1 15

Constructors in Java, cont. Every class should have a programmer defined constructor, that explicitly guarantees correct initialization of new objects. // redefined Coin class public class Coin { public static final int HEADS = 0; public static final int TAILS = 1; private int face; // the constructor public Coin () { face = TAILS; // method in object flip(); // method on other object otherobject.domoreinitialization(); OOP: Object-Oriented Programming, Part 1 16

Constructors and Cloning in Java public class Car { // instance variables private String make; private String model; private double price; /** The default constructor */ public Car() { this("", "", 0.0); // must be the first thing /** Construtor that assigns values to instance vars */ public Car(String make, String model, double price) { this.make = make; this.model = model; this.price = price; /** Cloning in Java overwrites the Object.clone() */ public Object clone() { // note the return type return new Car(make, model, price); OOP: Object-Oriented Programming, Part 1 17

Constructor Initialization public class Garage { Car car1 = new Car(); static Car car2 = new Car(); // created on first access public class Garage1 { Car car1; static Car car2; // Explicit static initialization static { car2 = new Car(); OOP: Object-Oriented Programming, Part 1 18

Constructor vs. Method Similarities Can take arguments all pass-by-value Can be overloaded Access modifiers can be specified (e.g., private or public) Can be final (covered later) Dissimilarties Has fixed name (same as the class) No return value returns a reference to object Special call via new operator new Car() Cannot be called by methods Default constructor can by synthesised by the system Cannot be declared static it is in fact a static method! OOP: Object-Oriented Programming, Part 1 19

Object Descrution in Java, cont. class MemoryUsage{ /** Dummy class to take up mem */ int id; /** Id of object */ String name; /** Name of object */ MemoryUsage(int id){ /** Constructor */ this.id = id; this.name = "Name: " + id; /** Overwrite the finalize method */ public void finalize(){ System.out.println("Goodbye cruel world " + this.id); public class Cleanup{ public static void main(string[] args){ for (int i = 0; i < 999; i++){ // allocate and discard MemoryUsage m = new MemoryUsage(i); if (i % 100 == 0){ System.gc(); OOP: Object-Oriented Programming, Part 1 20

Value vs. Object A value is a data element without identity that cannot change state. An object is an encapsulated data element with identity, state, and behavior. An object can behave like value (or record). Is it a good idea? Values in Java are of the primitive type byte, short, int, long, float, double, boolean, and char. Wrapper classes exists in Java for make the primitive type act as objects. OOP: Object-Oriented Programming, Part 1 21

Strings in Java Strings in Java are of the class String. Objects of class String behave like values. Characteristics of Strings The notation "fly" instantiates the class String and initialize it with the values "f"', "l", and "y". The class String has many different constructors. Values in a string cannot be modified (use StringBuffer instead). Class String redefines the method equals() from class Object. OOP: Object-Oriented Programming, Part 1 22

Equality Are the references a and b equal? Reference Equality Returns whether a and b points to the same object. Shallow Equality Returns whether a and b are structurally similar. One level of objects are compared. Deep Equality Returns where a and b have object-networks that are structurally similar. Multiple level of objects are compared recursively. Reference Equality Shallow Equality Deep Equality OOP: Object-Oriented Programming, Part 1 23

Equality Examples var1 var2 reference equal make: BMW model: M1 engine: ref cylinders: 6 KW: 130 var1 var2 make: BMW model: M1 engine: ref make: BMW model: M1 engine: ref cylinders: 6 KW: 130 shallow equal OOP: Object-Oriented Programming, Part 1 24

Equality Examples, cont. var1 make: BMW model: M1 engine: ref cylinders: 6 KW: 130 var2 make: BMW model: M1 engine: ref cylinders: 6 KW: 130 deep equal OOP: Object-Oriented Programming, Part 1 25

== Types of Equality in Java Equality on primitive data types 8 == 7 'b' == 'c' Reference equality on object references onepoint == anotherpoint Strings are special String s1 = "hello"; String s2 = "hello"; if (s1 == s2){ System.out.println(s1 + " equals" + s2); equals Method on the class java.lang.object. Default works like reference equality. Can be refined in subclass onepoint.equals(anotherpoint) OOP: Object-Oriented Programming, Part 1 26

equals example public class Car { // snip /** Gets the make inst variable(helper function). */ public String getmake() { return make; // snip /** * Implements the equals method * @see java.lang.object#equals(java.lang.object) */ public boolean equals(object o) { return o instanceof Car // is it a Car object? && ((Car) o).getmake() == this.make && ((Car) o).getmodel() == this.model && ((Car) o).getprice() == this.price; // relies on short circuiting OOP: Object-Oriented Programming, Part 1 27

Summary Instance variables Strings are treated specially in Java Methods All computation should be done in methods Overloading is generally a good thing Initialization is critical for objects Java guarantees proper initialization using constructors Source of many errors in C Java helps clean-up with garbage collection Only memory is clean, close those file handles explicitly! No memory leaks, "show stopper" in a C/C++ project! Equality (three types of equality) OOP: Object-Oriented Programming, Part 1 28

Arrays in Java Not pointers like in C, Bounds checking at run-time int[] numbers; // equivalent int number[]; int[] numbers = {1, 2, 3, 4, 5, 6, 7; The size is fixed at compile-time! int[] numbers = new Integer[getSize()]; The size is fixed at run-time! Cannot be resized for (int i = 0; i < numbers.length; i++){ System.out.println(numbers[i]); OOP: Object-Oriented Programming, Part 1 29