CS 2110 AEW. Machine Language. Outline. Assembly Language. High-Level Language 1/26/2012

Similar documents
CS 2110 AEW SIGN UP FOR 1 CREDIT S/U COURSE!!!

10/19/11. Announcements. Java Review. More Announcements. Today A Smorgasbord. Assembly Language. Machine Language. Assignment 1 has been posted

Java Review. Lecture 2 CS 2110 Fall 2011

Announcements. Java Review. More Announcements. Today. Assembly Language. Machine Language

JAVA REVIEW Lecture 2 CS2110 Fall 2010

CS 113: Introduction to

SOFTWARE ENGINEERING. Lecture 4 CS2110 Spring 2013

... picking up where we stopped SOFTWARE ENGINEERING. Interfaces 28/01/2013. Example: Overriding tostring. Example: Overriding tostring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Java Object Oriented Design. CSC207 Fall 2014

Rules and syntax for inheritance. The boring stuff

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Java Fundamentals (II)

COP 3330 Final Exam Review

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Chapter 1 Getting Started

Data Abstraction. Hwansoo Han

CS 251 Intermediate Programming Methods and More

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

G Programming Languages - Fall 2012

Inheritance and Interfaces

CS260 Intro to Java & Android 03.Java Language Basics

Derived and abstract data types. TDT4205 Lecture 15

Java: introduction to object-oriented features

1 Shyam sir JAVA Notes

CS-202 Introduction to Object Oriented Programming

Concepts of Programming Languages

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS 251 Intermediate Programming Methods and Classes

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Introduction to Inheritance

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Programming II (CS300)

Inheritance (Part 5) Odds and ends

Introduction to Programming Using Java (98-388)

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Chapter 9 Inheritance

CSE 401/M501 Compilers

CSC207 Week 3. Larry Zhang

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

PROGRAMMING LANGUAGE 2

Declarations and Access Control SCJP tips

Introduction to Java

Programming II (CS300)

ECE 122. Engineering Problem Solving with Java

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Grade Weights. Language Design and Overview of COOL. CS143 Lecture 2. Programming Language Economics 101. Lecture Outline

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

C a; C b; C e; int c;

Chapter 10 :: Data Abstraction and Object Orientation

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

INSTRUCTIONS TO CANDIDATES

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Lecturer: William W.Y. Hsu. Programming Languages

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

CPS 506 Comparative Programming Languages. Programming Language

A Short Summary of Javali

CS61B Lecture #8: Object-Oriented Mechanisms

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

C++ Important Questions with Answers

Lecture 02, Fall 2018 Friday September 7

CSE 431S Type Checking. Washington University Spring 2013

2. The object-oriented paradigm

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Pace University. Fundamental Concepts of CS121 1

Language Features. 1. The primitive types int, double, and boolean are part of the AP

BM214E Object Oriented Programming Lecture 4

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

1 Method Signatures and Overloading (3 minutes, 2 points)

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

CS/ENGRD 2110 SPRING 2018

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

TeenCoder : Java Programming (ISBN )

Arrays Classes & Methods, Inheritance

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

Practice for Chapter 11

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

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Java and C CSE 351 Spring

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Forth Meets Smalltalk. A Presentation to SVFIG October 23, 2010 by Douglas B. Hoffman

BM214E Object Oriented Programming Lecture 8

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Object-Oriented Concepts

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Transcription:

CS 2110 AEW SIGN UP FOR 1 CREDIT S/U COURSE!!! Students enrolled in AEWs, on average, earn a HIGHER GRADE in the course than those not enrolled in the AEW Get EXTRA PRACTICE solving problems so that course assignments are easier to complete FREE FOOD every class!!! CLASS TIME: Fridays 2:30PM-4:25PM Olin 216 CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 2: Java Review To add the course: just add ENGRG 1011 on Student Center Email Jennifer Doughty (jad359) for more details or if you have questions A brief (biased) history of programming languages Review of some Java/OOP concepts Outline Used with the earliest electronic computers (1940s) Machines use vacuum tubes instead of transistors Programs are entered by setting switches or reading punch cards All instructions are numbers Machine Language Example code 0110 0001 0000 0110 add reg1 6 An idea for improvement Use words instead of numbers Result: Assembly Language Java tips, trick, and pitfalls 3 4 Idea: Use a program (an assembler) to convert assembly language into machine code Early assemblers were some of the most complicated code of the time (1950s) Assembly Language Example code ADD R1 6 MOV R1 COST SET R1 0 JMP TOP Idea for improvement Let s make it easier for humans by designing a high-level computer language Result: high-level languages Idea: Use a program (a compiler or an interpreter) to convert high-level code into machine code Pro Easier for humans to write, read, and maintain code Con The resulting program will never be as efficient as good assembly-code Waste of memory Waste of time High-Level Language The whole concept was initially controversial FORTRAN (mathematical FORmula TRANslating system) was designed with efficiency very much in mind 5 6 1

FORTRAN ALGOL Initial version developed in 1957 by IBM Example code C SUM OF SQUARES ISUM = 0 DO 100 I=1,10 ISUM = ISUM + I*I 100 CONTINUE FORTRAN introduced many high-level language constructs still in use today Variables & assignment Loops Conditionals Subroutines Comments ALGOL = ALGOrithmic Language Developed by an international committee First version in 1958 (not widely used) Second version in 1960 (widely used) Sample code comment Sum of squares begin integer i, sum; for i:=1 until 10 do sum := sum + i*i; end ALGOL 60 included recursion Pro: easier to design clear, succinct algorithms Con: too hard to implement; too inefficient 7 8 COBOL = COmmon Business Oriented Language Developed by the US government (about 1960) Design was greatly influenced by Grace Hopper Goal: Programs should look like English Idea was that anyone should be able to read and understand a COBOL program COBOL COBOL included the idea of records (a single data structure with multiple fields, each field holding a value) These languages introduced and popularized Object Oriented Programming (OOP) Simula was developed in Norway as a language for simulation in the 60s Smalltalk was developed at Xerox PARC in the 70s These languages included Classes Objects Subclasses & Inheritance Simula & Smalltalk [Wikipedia] 9 10 Java includes Assignment statements, loops, conditionals from FORTRAN (but syntax from C) Recursion from ALGOL Fields from COBOL OOP from Simula & Smalltalk Java 1995 JavaTM and logo Sun Microsystems, Inc. We assume you already know Java Classes and objects Static vs instance fields and methods Local variables Primitive vs reference types Private vs public vs package Constructors Method signatures Arrays Subtypes and Inheritance, Shadowing 11 12 2

Java is object oriented In most prior languages, code was executed line by line and accessed variables or record In Java, we think of the data as being organized into objects that come with their own methods, which are used to access them This shift in perspective is critical When coding in Java one is always thinking about which object is running this code? Dynamic vs. Static Some kinds of information is static There can only be one instance Like a global variable in C or C++ (or assembler) In languages like FORTRAN, COBOL most data is static. Object-oriented information is dynamic Each object has its own private copy When we create a new object, we make new copies of the variables it uses to keep its state Languages like C and C++ allow us to allocate memory at runtime, but don t offer a lot of help for managing it In Java this distinction becomes very important Constructors Called to create new instances of a class Default constructor initializes all fields to default values (0 or null) class Thing { int val; Run once when class is loaded Used to initialize static objects class StaticInit { Static Initializers static String[] courses = new String[2]; Thing(int val) { this.val = val; Thing() { this(3); Thing one = new Thing(1); Thing two = new Thing(2); Thing three = new Thing(); 15 static { courses[0]="cs 2110"; courses[1]="cs 2112";... 16 Static methods and variables If a method or a variable is declared static there will be just one instance for the class Otherwise, we think of each object as having its own version of the method or variable Anyone can call a static method or access a static variable But to access a dynamic method or variable Java needs to know which object you mean Static vs Instance Example class Widget { static int nextserialnumber = 10000; int serialnumber; Widget() { serialnumber = nextserialnumber; nextserialnumber++; Widget a = new Widget(); Widget b = new Widget(); Widget c = new Widget(); System.out.println(a.serialNumber); System.out.println(b.serialNumber); System.out.println(c.serialNumber); 18 3

Names Refer to my static and instance fields & methods of same class/object by (unqualified) name: serialnumber nextserialnumber Refer to static fields & methods in another class using name of the class Widget.nextSerialNumber Refer to instance fields & methods of another object using name of the object a.serialnumber Example System.out.println(a.serialNumber) out is a static field in class System The value of System.out is an instance of a class that has an instance method println(int) If an object must refer to itself, use this class Thing { int val; A Common Pitfall local variable shadows field boolean setval(int v) { int val = v; you would like to set the instance field val = v but you have declared a new local variable val assignment has no effect on the field val 19 20 The main Method Can be called from anywhere A class method; don t need an object to call it No return value Method must be named main Avoiding trouble Keep in mind that main is a static method Hence anything main calls needs to have an associated object instance, or itself be static Use of static methods is discouraged class Thing { int counter; static int sequence; public static void main(string[] args) {... Parameters passed to program, either from command line or from Run / Debug dialog box in Eclipse 21 int c = ++counter; // Illegal: counter is assoc // with an object of type // Thing. But which object? int s = ++sequence;// Legal: sequence is // static too Overloading of Methods A class can have several methods of the same name But all methods must have different signatures The signature of a method is its name plus types of its parameters Example: String.valueOf(...) in Java API There are 9 of them: valueof(boolean); valueof(int); valueof(long);... Parameter types are part of the method s signature 23 Primitive vs Reference Types Primitive types int, short, long, float, byte, char, boolean, double efficient 1 or 2 words not an Object unboxed Reference types objects and arrays String, int[], HashSet usually require more memory can have special value null can compare null with ==,!= generate NullPointerException if you try to dereference null x true x nonzero val next true 23 null 24 4

= = is not equals( ) == tests whether variables hold identical values shallow equality works fine for primitive types equals() test whether two objects (e.g., String) contain equivalent data deep equality need to use for reference types Two different strings with value x = ; y = ; x == y x y = = vs equals( ) for String What you wrote. Value? What you should write. xy" == new String("xy ) False "xy".equals(new String("xy")) "xy" == "xy" True "xy".equals("xy") "xy" == "x" + "y" True "xy".equals("x" + "y") To compare object contents, override Object.equals() But if you do this, must also override Object.hashCode() (more on this later) 25 26 Arrays are reference types Array elements can be reference types or primitive types E.g., int[] or String[] If a is an array, a.length is its length Its elements are a[0], a[1],..., a[a.length-1] The length is fixed! a Arrays String[] a = new String[4]; a.length == 4; a[2] = hello ; 0 1 2 3 null null null null 27 Accessing Array Elements Sequentially public class CommandLineArgs { System.out.println(args.length); // old-style for (int i = 0; i < args.length; i++) { System.out.println(args[i]); // new style for (String s : args) { System.out.println(s); 28 superclass of EPuzzle subclass of Object subclass of Puzzle and Object superclass of EPuzzle and Puzzle EPuzzle Class Hierarchy Puzzle Object. Every class (except Object) has a unique immediate superclass, called its parent Array Overriding A method in a subclass overrides a method in superclass if: both methods have the same name, both methods have the same signature (number and type of parameters and return type), and both are static methods or both are instance methods Methods are dispatched according to the runtime type of the object (dynamic binding / late binding) 29 30 5

Casting and Method Dispatch class A { public int m() {... class B extends A { public int m() {... B b = new B(); b.m(); A a = new B(); //upcasting a.m(); Always calls methods of the class that was use for creation with new. Unexpected Consequence class A { public int m() {... class B extends A { private int m() {... //illegal! A a = new B(); //upcasting a.m(); //would invoke private method in // class B at runtime! An overriding method cannot have more restricted access than the method it overrides 31 32 Accessing Overridden Methods Suppose a class S overrides a method m in its parent Methods in S can invoke the overridden method in the parent as super.m() In particular, can invoke the overridden method in the overriding method! Caveat: cannot compose super more than once as in super.super.m() 33 Overloading Revisited class Base { class Derived extends Base { class Test{ public void m (Derived b){ System.out.println("Test.m(Derived)"); public void m (Base a){ System.out.println("Test.m(Base)"); public static void main(string []args){ Test t = new Test(); Base b = new Base(); Base d = new Derived(); t.m(b); t.m(d); Output: Test.m(Base) Test.m(Base) 34 34 Shadowing Like overriding, but for fields instead of methods Superclass: variable v of some type Subclass: variable v perhaps of some other type Method in subclass can access shadowed variable using super.v Variable references are resolved using static binding (i.e., at compile-time), not dynamic binding (i.e., not at runtime) Variable reference r.v uses the static type (declared type) of the variable r, not the runtime type of the object referred to by r Shadowing variables is bad medicine and should be avoided Experimentation and Debugging Don't be afraid to experiment if you are not sure how things work Documentation isn t always clear Interactive Development Environments (IDEs), e.g. Eclipse, make this easier Debugging Do not just make random changes, hoping something will work Think about what could cause the observed behavior Isolate the bug An IDE makes this easier by providing a Debugging Mode Can set breakpoints, step through the program while watching chosen variables 35 39 6