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

Similar documents
Java Review. Object Orientation

CMSC433, Fall 2008 Programming Language Technology and Paradigms. Java Review. Adam Porter 9/4/08

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

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Binghamton University. CS-140 Fall Dynamic Types

CH. 2 OBJECT-ORIENTED PROGRAMMING

Java Object Oriented Design. CSC207 Fall 2014

1 Shyam sir JAVA Notes

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

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

Example: Count of Points

Class, Variable, Constructor, Object, Method Questions

Programming Languages and Techniques (CIS120)

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

Java Fundamentals (II)

15CS45 : OBJECT ORIENTED CONCEPTS

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

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

Java: introduction to object-oriented features

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

CS260 Intro to Java & Android 03.Java Language Basics

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

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

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

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

CS-202 Introduction to Object Oriented Programming

Declarations and Access Control SCJP tips

Exercise: Singleton 1

CS Programming I: Inheritance

CS 231 Data Structures and Algorithms, Fall 2016

Example: Count of Points

Chapter 1 Getting Started

Data Abstraction. Hwansoo Han

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

JAVA MOCK TEST JAVA MOCK TEST II

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

ITI Introduction to Computing II

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Practice for Chapter 11

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

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

CMSC 132: Object-Oriented Programming II

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

Programming overview

ITI Introduction to Computing II

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

G Programming Languages - Fall 2012

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Inheritance -- Introduction

Selected Questions from by Nageshwara Rao

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Inheritance (continued) Inheritance

Operators and Expressions

Points To Remember for SCJP

COE318 Lecture Notes Week 6 (Oct 10, 2011)

Inheritance (Part 5) Odds and ends

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

Inheritance and Polymorphism

Computer Science 1 Ah

Full file at Chapter 2 - Inheritance and Exception Handling

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

CS 251 Intermediate Programming Inheritance

Introduction to Programming Using Java (98-388)

Rules and syntax for inheritance. The boring stuff

Compaq Interview Questions And Answers

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming Languages and Techniques (CIS120)

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

20 Most Important Java Programming Interview Questions. Powered by

What is Inheritance?

More Relationships Between Classes

Big software. code reuse: The practice of writing program code once and using it in many contexts.

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

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

Java Language Features

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Making New instances of Classes

Instance Members and Static Members

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

CMSC 132: Object-Oriented Programming II

Inheritance and Polymorphism

CLASS DESIGN. Objectives MODULE 4

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Computer Components. Software{ User Programs. Operating System. Hardware

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

COP 3330 Final Exam Review

JAVA Programming Language Homework I - OO concept

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

25. Generic Programming

STRUCTURING OF PROGRAM

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

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Selected Java Topics

CS S-08 Arrays and Midterm Review 1

Transcription:

CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised Friday to make it better, easier A few subsequent small clarifications since then Important: Must change WebServer to use -Dport=... Class accounts e-mailed out Contact me if you didn t get one 33 Demo Objects and Variables Running basic web server Finding hostname of machine Connecting with web browser Telnet to a web server 34 Variables of a primitive type contain values e.g., byte, char, int,... int i = 6; Uninitialized values contain 0 Assignment copies values Variables of other types contain references to the heap int[] a = new int[3]; Objects are allocated with new Uninitialized object references are null Assignment copies references, not the objects themselves 35 Example Example: Assignments int i = 6; int j; // uninitialized int [] a = {1, 3, 5, 7, 9; int [] b = new int[3]; String s = abcdef ; String t = null; j = i; b = a; t = s; 36 37 1

Garbage Collection What happens to array [0, 0, 0] in previous example? It is no longer accessible When Java performs garbage collection (GC) it will automatically reclaim the memory it uses Notice: No free() or delete in Java Makes it much easier to write correct programs Most of the time, very efficient Mutability An object is mutable if its state can change Example: Arrays are mutable An object is immutable if its state never changes Once its been initialized Example: Strings in Java are not mutable There are no methods to change the state of a string 38 39 Example: Mutability Method Invocation a[1] = 0; // also changes b[1] Syntax o.m(arg1, arg2,..., argn); Moral: Always be careful when you have aliasing Multiple references to the same object Run the m method of object o with arguments arg1...argn Two ways to reuse method names: Methods can be overridden Methods can be overloaded 40 41 Overriding Define a method also defined by a superclass class Parent { int cost; cost += x; class Child extends Parent { if (x > 0) cost += x; Overriding (cont d) Method with same name and argument types in child class overrides method in parent class Arguments and result types must be identical otherwise you are overloading the method Must raise the same or fewer exceptions Can override/hide instance variables both variables will exist, but don t do it 42 43 2

Declared vs. Actual Types Method Dispatch The actual type of an object is its allocated type Integer o = new Integer(1); A declared type is a type at which an object is being viewed Object o = new Integer(1); void m(object o) {... Each object always has one actual type, but can have many declared types 44 Consider again o.m(arg1, arg2,..., argn); Only compiles if o s declared type contains an appropriate m method Method corresponding to o s actual type is what is invoked 45 Dynamic Dispatch Example public class A { String f() { return I m an A! ; public class B extends A { String f() { return I m a B! ; public static void main(string args[]) { A a = new B(); B b = new B(); System.out.println(a.f() + b.f()); Prints I m a B! I m a B! Self Reference this refers to the object the method is invoked on Thus can access fields of this object as this.x or this.y But more concise to omit super refers to the same object as this But used to access methods/variables in superclass 46 47 Example of super Call a superclass method from a subclass class Parent { int cost; cost += x; class Child extends Parent { if (x > 0) super.add(x); 48 Overloading Methods with the same name, but different parameters (count or types) are overloaded Invocation determined by name and types of params Not return value or exceptions Resolved at compile-time, based on declared types Be careful: Easy to inadvertently overload instead of override! 49 3

Overloading Example class Parent { int cost; cost += x; void add(object s) throws NumberFormatException { cost += Integer.parseInt((String)s); class Child extends Parent { void add(string s) throws NumberFormatException { if (x > 0) cost += Integer.parseInt(s); Child c = new Child(); Prints -1 c.add((object) -1 ); System.out.println(c.cost); 50 Static Fields and Methods static stored with the class Static fields allocated once, no matter how many objects created Static methods are not specific to any class instance, so cannot refer to this or super Can reference class variables and methods through either class name or an object ref Clearer to reference via the class name 51 Static Field Example Some Static Fields and Methods Class definition Public class Foo { int foo; static int bar; Class implementation Foo int bar; Objects of class Foo int foo int foo int foo public static void main(string args[]) { public class Math { public final static PI = 3.14159 ; public class System { public static PrintStream out = ; 52 53 Static Method Dispatch Let B be a subclass of A, and suppose we have A a = new B(); Declared type A Actual type B Then Class (static) methods invoked on a will get the methods for the declared type A Invoking class methods via objects strongly discouraged Instead, invoke through class A.m() instead of a.m() Static Method Dispatch Example public class A { static String g() { return This is A! ; public class B extends A { static String g() { return This is B! ; public static void main(string args[]) { A a = new B(); B b = new B(); System.out.println(a.g() + b.g()); Prints This is A! This is B! 54 55 4

Better Use of Static Methods Other Field Modifiers public class A { static String g() { return This is A! ; public class B extends A { static String g() { return This is B! ; public static void main(string args[]) { System.out.println(A.g() + B.g()); Prints This is A! This is B! 56 final can t be changed Must be initialized in declaration or in constructor transient, volatile Will cover later public, private, protected, package (default) Respectively, visible everywhere, only within this class, within same package or subclass, within same package 57 Other Method Modifiers Poor man s polymorphism final this method cannot be overridden Useful for security Allows compiler to inline method abstract no implementation provided Class must be abstract public visible outside this package native, synchronized Will cover later Every object is a subtype of Object Thus, a data structure Set that implements sets of Objects can also hold Strings or images or anything! The trick is getting them back out: When given an Object, you have to downcast it 58 59 Downcasting (Bar) foo Run-time exception if object reference by foo is not a subtype of Bar Compile-time error if Bar is not a subtype of foo (i.e., it always throws an exception) No effect at run-time; just treats the result as if it were of type Bar o instanceof Foo returns true iff o is a subtype of Foo 60 Example class DumbSet { public void insert(object o) {.. public bool member(object o) {.. public Object any() {.. class MyProgram { public static void main(string[] args) { DumbSet set = new DumbSet(); String s1 = foo ; String s2 = bar ; set.insert(s1); set.insert(s2); System.out.println(s1+ in set? +set.member(s1)); String s = (String)set.any(); // downcast System.out.println( got +s); 61 5

Wrapper (Boxed) classes Integer, Boolean, Double, Are subclasses of Object Useful/required for polymorphic methods HashTable, LinkedList, Used in reflection classes Array types Misfeature: suppose S is a subtype of T then S[] is a subtype of T[] Object[] is a supertype of all arrays of reference types Include many utility functions For example, convert to/from String 62 63 Example: Object[] public class TestArrayTypes { public static void reversearray(object [] A) { for(int i=0, j=a.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; public static void main(string [] args) { reversearray(args); for(int i=0; i < A.length; i++) System.out.println(args[i]); 64 Problem with Subtyping Arrays public class A {... public class B extends A { void newmethod();... void foo(void) { B[] bs = new B[]; A[] as; as = bs; // Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newmethod(); // (2) Program compiles without warning Java must generate run-time check at (1) to prevent (2) Type written to array must be subtype of declared type 65 6