Java Object Model. Or, way down the rabbit hole

Size: px
Start display at page:

Download "Java Object Model. Or, way down the rabbit hole"

Transcription

1 Java Object Model Or, way down the rabbit hole 1

2 Type Definition: a set of values and a set of operations that can be applied to those values Java is a strongly-typed language: compiler & runtime system ensure that programs don t violate type system rules Compiler catches most illegal operation attempts Java virtual machine catches a few (e.g. invalid casts) By contrast, C/C++ not strongly typed 2

3 Types in Java Primitive: int, double, char, boolean, etc. Class Interface Array Array in itself is distinct type Individual array elements are of some component type Null 3

4 Values in Java Every value is one of the following: Value of a primitive type (e.g. 1.4, -9, c ) Reference to a class object Reference to an array null Notes: No such thing as a value of an interface type Void is not a data type just a method tag to indicate no return value 4

5 Subtype relationship Subtype contains subset of values of a given type Can use subtype where supertype is specified 5

6 S is a subtype of T if: 1. S and T are the same type 2. S and T are both class types, and T is a direct or indirect superclass of S 3. S is a class type, T is an interface type, and S or one of its superclasses implements T 4. S and T are both interface types, and T is a direct or indirect superinterface of S 5. S and T are both array types, and the component type of S is a subtype of the component type of T 6. S is not a primitive type and T is the type Object 7. S is an array type and T is Cloneable or Serializable 8. S is the null type and T is not a primitive type 6

7 Examples ListIterator is a subtype of Iterator Container is a subtype of Component FlowLayout is a subtype of Layout Manager JButton is a subtype of Component 7

8 Examples Rectangle[] is a subtype of Shape[] int[] is a subtype of Object int is not a subtype of long long is not a subtype of int int[] is not a subtype of Object[] 8

9 Array Types Recall rule 5: S[] is a subtype of T[] if S is a subtype of T Example: Rectangle [] r = new Rectangle[10]; Can store object r in an array of Shape, since Rectangle is a subset of Shape: Shape [] s = r; Variables r and s both refer to the same array 9

10 Example continued What happens if a non-rectangle Shape is stored in s[]? Throws ArrayStoreException at runtime Every array object remembers its component type Could store a subtype of Rectangle (but not just of Shape) without throwing exception 10

11 Primitive type wrappers Many services in Java API deal with Objects; for example, ArrayLists are collections of Objects Primitive types are not subtypes of Object Useful to have classes to wrap primitive types so they can avail themselves of Object services 11

12 Wrapper classes in Java Wrapper classes exist for all primitive types: Integer, Short, Long Byte, Character Float, Double Boolean Wrapper classes are immutable 12

13 Wrapper class methods Constructor take primitive type argument: double num = ; Double d = new Double(num); Can unwrap to get primitive value: num = d.doublevalue(); Some wrappers have parse methods that convert from String to primitive: String s = ; int n = Integer.parseInt(s); 13

14 Type inquiry Can use instanceof operator to test whether an expression is a reference to an object of a given type or one of its subtypes Operator returns true if expression is a subtype of the given type; otherwise (including in the case of a null expression) returns false 14

15 Example using instanceof JPanel picpanel = new JPanel(); ArrayList images = new ArrayList(); for (int x=0; x<images.size(); x++) { Object o = images.get(x); if (o instanceof Icon) { Icon pic = (Icon)o; picpanel.add(pic); } } 15

16 Notes on instanceof Can test whether value is subtype of given type, but doesn t distinguish between subtypes In previous example, o could be any kind of Icon (since Icon is an interface, couldn t be an Icon per se) 16

17 Getting exact class of object Can get exact class of object reference by invoking getclass() method Method getclass() returns an object of type Class; can invoke getname() on Class object to retrieve String containing class name: System.out.println(o.getClass().getName()); 17

18 Class object Type descriptor Contains information about a given type, e.g. type name and superclass 18

19 Ways to obtain Class object Call getclass() on an object reference Call static Class method forname(): Class c = Class.forName( java.awt.rectangle ); Add suffix.class to a type name to obtain a literal Class object: Class c = Rectangle.class; 19

20 Notes on Class type There is exactly one Class object for every type loaded in the virtual machine Class objects describe any type, including primitive types Can use == to test whether two Class objects describe same type: if (o.getclass() == Rectangle.class) True if o is exactly a Rectangle (not a subclass) 20

21 Arrays and getclass() When applied to an array, getclass() returns a Class object that describes the array type Use Class method getcomponenttype() to get a Class object describing the array s components Use Class method isarray() to determine whether or not an object is an array 21

22 Arrays and Class.getName() Array name is built from these rules: [type Where type is one of the following: B: byte C: char D: double F: float I: int J: long S: short Z: boolean For non-primitive types, replace type with Lname; (where name is the name of the class or interface note semicolon) 22

23 Reflection Mechanism by which a program can analyze its objects & their capabilities at runtime Java API includes several reflection classes, described on next slide 23

24 Reflection Classes Class: describes a type Package: describes a package Field: describes field; allows inspection, modification of all fields Method: describes method, allows its invocation on objects Constructor: describes constructor, allows its invocation Array: has static methods to analyze arrays 24

25 Class class object Includes class name and superclass of an object, as we have already seen; also includes: interface types class implements package of class names & types of all fields names, parameter types, return types of all methods parameter types of all constructors 25

26 Class class methods getsuperclass() returns Class object that describes superclass of a given type; returns null if type is Object or is not a class getinterfaces() returns array of Class objects describing interface types implemented or extended; if type doesn t implement or extend any interfaces, returns array of length 0 (only returns direct superinterfaces) 26

27 Class class methods getpackage() returns Package object; Package has getname() method which returns String containing package name getdeclaredfields() returns array of Field objects declared by this class or interface includes public, private, protected & packagevisible fields includes both static & instance fields does not include superclass fields 27

28 Field class methods getname(): returns String containing field name gettype(): returns Class describing field type getmodifiers(): returns an int whose various bits are set to indicate whether field is public, private, protected, static, or final: use static Modifier methods ispublic, isprivate, isprotected, isstatic, isfinal to test this value 28

29 Example - prints all static fields of java.lang.math Field[] fields = Math.class.getDeclaredFields(); for (int x = 0; x < fields.length; x++) if(modifier.isstatic(fields[x].getmodifiers())) System.out.println(fields[x].getName()); 29

30 More Class class methods getdeclaredconstructors() returns array of Constructor objects describing class constructors Constructor object has method getparametertypes that returns an array of Class objects describing the constructor s parameters 30

31 Example: printing Rectangle constructor information Constructor cons[] = Rectangle.class.getDeclaredConstructors(); for (int x=0; x < cons.length; x++) { Class [] params = cons[x].getparametertypes(); System.out.println( Rectangle( ); for (int y=0; y < params.length; y++) { if(y > 0) System.out.print(, ); System.out.print(params[y].getName()); } System.out.println( ) ); } 31

32 Output from example Rectangle() Rectangle(java.awt.Rectangle) Rectangle(int, int, int, int) Rectangle(int, int) Rectangle(java.awt.Point, java.awt.dimension) Rectangle(java.awt.Point) Rectangle(java.awt.Dimension) 32

33 Class class s getdeclaredmethods() method Returns array of Method objects Method object methods include: getparametertypes(): returns array of parameter types getname(): returns method name getreturntype(): returns Class object describing return value type 33

34 Obtaining single Method or Constructor objects Class s getdeclaredmethod() (note the singular) returns a Method object if supplied with a method name and array of parameter objects: Method m = Rectangle.class.getDeclaredMethod( contains, new Class[]{int.class, int.class}); For Constructor object: Constructor c = Rectangle.class.getDeclaredConstructor(new Class[] {}); 34

35 Method methods invoke(): can be used to call a method described by a Method object - need to: supply implicit parameter (null for static methods) first argument, representing calling object supply array of explicit parameter values (need to wrap primitive types) if method returns a value, invoke returns an Object; need to cast or unwrap return value, as appropriate 35

36 Example - saying hello the hard way import java.lang.reflect.*; import java.io.*; public class SayHello { public static void main(string[]args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m = PrintStream.class.getDeclaredMethod ( println, new Class[] {String.class}); m.invoke(system.out, new Object[] { Hello! }); } } 36

37 Example with return value Method m = Math.class.getDeclaredMethod( sqrt, new Class[] {double.class}); Object r = m.invoke(null, new Object[] {new Double(10.24)}); double x = ((Double) r).doublevalue(); 37

38 Inspecting objects Can use reflection mechanism to dynamically look up object fields as program runs To allow access to a field, call its setaccessible() method; example: Class c = object.getclass(); Field f = c.getdeclaredfield(name); f.setaccessible(true); 38

39 Inspecting objects Once granted access, you can read and write any field of the object: Object value = f.get(object); f.set(object, value); Notes: f must be a Field that describes a field of object; otherwise, get and set throw exception if field type is primitive, get returns & set expects a wrapper if field is static, supply null for object 39

40 Inspecting array elements Field allows read/write access to arbitrary field of object; Array works similarly on array objects for array a with index x: get() method: Object value = Array.get(a,x) set() method: Array.set(a,x,value); 40

41 Inspecting array elements Finding length of array a: int n = Array.getLength(a); Creating new array (twice as large) with static method newinstance(): Object newarray = Array.newInstance( a.getclass().getcomponenttype(), 2 * Array.getLength(a) + 1); System.arraycopy(a, 0, newarray, 0, Array.getLength(a)); a = newarray; 41

42 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass of Object Methods of Object include: String tostring() boolean equals (Object other) int hashcode() Object clone() 42

43 Method tostring() Returns String representation of object; describes state of object Automatically called when: Object is concatenated with a String Object is printed using print() or println() Object reference is passed to assert statement of the form: assert condition : object 43

44 Example Rectangle r = new Rectangle (0,0,20,40); System.out.println(r); Prints out: java.awt.rectangle[x=0,y=0,width=20,height=40] 44

45 More on tostring() Default tostring() method just prints (full) class name & hash code of object Not all API classes override tostring() Good idea to implement for debugging purposes: Should return String containing values of important fields along with their names Should also return result of getclass().getname() rather than hard-coded class name 45

46 Overriding tostring(): example public class Employee { public String tostring() { return getclass().getname() + "[name=" + name + ",salary=" + salary + "]"; }... } Typical String produced: Employee[name=John Doe,salary=40000] 46

47 Overriding tostring in a subclass Format superclass first Add unique subclass details Example: public class Manager extends Employee { public String tostring() { return super.tostring() + "[department=" + department + "]"; }... } 47

48 Example continued Typical String produced: Manager[name=Mary Lamb,salary=75000][department=Admin] Note that superclass reports actual class name 48

49 Equality testing Method equals() tests whether two objects have same contents By contrast, == operator test 2 references to see if they point to the same object (or test primitive values for equality) Need to define for each class what equality means: Compare all fields Compare 1 or 2 key fields 49

50 Equality testing Object.equals tests for identity: public class Object { public boolean equals(object obj) { return this == obj; }... } Override equals if you don't want to inherit that behavior 50

51 Overriding equals() Good practice to override, since many API methods assume objects have well-defined notion of equality When overriding equals() in a subclass, can call superclass version by using super.equals() 51

52 Requirements for equals() method Must be reflexive: for any reference x, x.equals(x) is true Must be symmetric: for any references x and y, x.equals(y) is true if and only if y.equals(x) is true Must be transitive: if x.equals(y) and y.equals(z), then x.equals(z) If x is not null, then x.equals(null) must be false 52

53 The perfect equals() method public boolean equals(object otherobject) { if (this == otherobject) return true; if (otherobject == null) return false; if (getclass()!= otherobject.getclass()) return false;... } 53

54 Hashing Technique used to find elements in a data structure quickly, without doing full linear search Important concepts: Hash code: integer value used to find array index for data storage/retrieval Hash table: array of elements arranged according to hash code Hash function: computes index for element; uses algorithm likely to produce different indexes for different objects to minimize collisions 54

55 Hashing in Java Java library contains HashSet and HashMap classes Use hash tables for data storage Since Object has a hashcode method, any type of object can be stored in a hash table 55

56 Default hashcode() Gives hash value based on memory address of object; consistent with default equals() method If you override equals(), you should also redefine hashcode() For class you are defining, use product of hash of each field and a prime number, then add these together result is hash code 56

57 Example public class Employee { public int hashcode() { return 11 * name.hashcode() + 13 * new Double(salary).hashCode(); }... } 57

58 Object copying Shallow copy Copy of an object reference is another reference to the same object Happens with assignment operator Deep copy Actual new object created, identical to original A.K.A cloning 58

59 Method clone() must fulfill 3 conditions X.clone()!= X X.clone().equals(X) X.clone().getClass() == X.getClass() 59

60 Object.clone() Default method is protected If a class wants clients to be able to clone its instances, must: Redefine clone() as public method Implement Cloneable interface 60

61 Cloneable Interface that specifies no methods: public interface Cloneable {} Strictly tagging interface; can be used to test if object can be cloned: if (x instanceof Cloneable) If class doesn t implement this interface, Object.clone() throws a CloneNotSupportedException (checked) 61

62 Example clone() method (v 1.0) public class Employee implements Cloneable { public Object clone() { try { return super.clone(); } catch(clonenotsupportedexception e) { return null; // won't happen } }... } 62

63 Shallow cloning Object.clone() uses assignment makes shallow copy of all fields If fields are object references, original and clone share common subobjects Not a problem for immutable fields (e.g. Strings) but programmer-written clone() methods must clone mutable fields Rule of thumb: if you extend a class that defines clone(), redefine clone() 63

64 Example clone() method (v 2.0) public class Employee implements Cloneable { public Object clone() { try { Employee cloned = (Employee) super.clone(); cloned.hiredate = (Date) hiredate.clone(); return cloned; } catch(clonenotsupportedexception e) { return null; } }... } 64

65 Components Component: a software construct that encapsulates more functionality than a single class Can use a set of components to construct an application without much additional programming Visual Basic/ActiveX controls exemplify the component model of programming

66 Components & Java Beans JavaBeans: Java s (partial) implementation of the component model Capabilities of a bean: Can execute methods Can reveal properties Can emit events

67 Bean Properties Not necessarily instance variables may be stored externally Have getter and setter methods (which may do more work than just/getting setting an instance variable, even if the property is an instance variable)

68 Bean Properties Java doesn t really support components directly: beans rely on naming conventions for standardization Setter method names start with set, getter with get (exception Boolean getters use is)

69 Beans & Façade pattern Java Beans work according to the Façade pattern: Each bean may consist of multiple classes, but a single class is chosen as the façade Clients call on façade method, which can call methods from other classes Façade class reveals subsystem class capabilities; subsystem classes don t need to be aware of the facade

70 Beans & Reflection Beans are intended to be edited in a builder environment (such an environment is built into NetBeans) When bean is loaded into builder environment, façade class is searched for methods that match the conventional naming scheme this is an example of the reflection mechanism at work

Material Java type system Reflection

Material Java type system Reflection CS1706 Intro to Object Oriented Dev II -Fall 04 Announcements Week 15 Final Exam: Tues. Dec. 14 @ 3:25pm Material Java type system Reflection Java Type System Type System is a set of values and the operations

More information

CS1007: Object Oriented Design and Programming in Java. Lecture #18 Mar 28 Shlomo Hershkop Announcement

CS1007: Object Oriented Design and Programming in Java. Lecture #18 Mar 28 Shlomo Hershkop Announcement CS1007: Object Oriented Design and Programming in Java Lecture #18 Mar 28 Shlomo Hershkop shlomo@cs.columbia.edu Homework released Start early Test often Goal: Announcement Waste time playing othello Learn

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Introduction to Reflection

Introduction to Reflection Introduction to Reflection Mark Allen Weiss Copyright 2000 1 What is Reflection The Class class Outline of Topics Run Time Type Identification (RTTI) Getting Class Information Accessing an arbitrary object

More information

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Creating an Immutable Class. Based on slides by Prof. Burton Ma Creating an Immutable Class Based on slides by Prof. Burton Ma 1 Value Type Classes A value type is a class that represents a value Examples of values: name, date, colour, mathematical vector Java examples:

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Lecture 9 : Basics of Reflection in Java

Lecture 9 : Basics of Reflection in Java Lecture 9 : Basics of Reflection in Java LSINF 2335 Programming Paradigms Prof. Kim Mens UCL / EPL / INGI (Slides partly based on the book Java Reflection in Action, on The Java Tutorials, and on slides

More information

Methods Common to all Classes

Methods Common to all Classes Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;

More information

For this section, we will implement a class with only non-static features, that represents a rectangle

For this section, we will implement a class with only non-static features, that represents a rectangle For this section, we will implement a class with only non-static features, that represents a rectangle 2 As in the last lecture, the class declaration starts by specifying the class name public class Rectangle

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms

More information

Expected properties of equality

Expected properties of equality Object equality CSE 331 Software Design & Implementation Dan Grossman Spring 2015 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins) A simple idea??

More information

java.lang.object: Equality

java.lang.object: Equality java.lang.object: Equality Computer Science and Engineering College of Engineering The Ohio State University Lecture 14 Class and Interface Hierarchies extends Object Runable Cloneable implements SmartPerson

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2016 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Object equality A

More information

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters Overloaded Methods Sending Messages Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Initialization & Cleanup 2 Overloaded Constructors Sending Parameters accessor method 3 4 Sending Parameters

More information

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: reflection

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: reflection Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: reflection Outline Introductory detour: quines Basic reflection Built-in features Introspection Reflective method invocation

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

equals() in the class Object

equals() in the class Object equals() in the class Object 1 The Object class implements a public equals() method that returns true iff the two objects are the same object. That is: x.equals(y) == true iff x and y are (references to)

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Kevin Zatloukal Summer 2017 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Overview Notions

More information

EPITA Première Année Cycle Ingénieur. Atelier Java - J3

EPITA Première Année Cycle Ingénieur. Atelier Java - J3 EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Overview 1 Imagination From 2 Plan 1 Imagination From Plan 1 Imagination From What is Reflection is the process

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

type conversion polymorphism (intro only) Class class

type conversion polymorphism (intro only) Class class COMP 250 Lecture 33 type conversion polymorphism (intro only) Class class Nov. 24, 2017 1 Primitive Type Conversion double float long int short char byte boolean non-integers integers In COMP 273, you

More information

JAVA. Reflection API. Java, summer semester

JAVA. Reflection API. Java, summer semester JAVA Reflection API 26.2.2013 1 Overview Reflection changes structure/state of objects Introspection exploring a structure of objects similar to RTTI in C++ but more powerful allows obtaining information

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

Reflection. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 28

Reflection. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 28 Reflection Computer Science and Engineering College of Engineering The Ohio State University Lecture 28 Motivating Problem Debugger/visualization tool Takes an object, any object Displays the methods one

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016 COMP 250 Lecture 32 polymorphism Nov. 25, 2016 1 Recall example from lecture 30 class String serialnumber Person owner void bark() {print woof } : my = new (); my.bark();?????? extends extends class void

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Concepts of Object-Oriented Programming Peter Müller

Concepts of Object-Oriented Programming Peter Müller Concepts of Object-Oriented Programming Peter Müller Chair of Programming Methodology Autumn Semester 2017 1.2 Introduction Core Concepts 2 Meeting the Requirements Cooperating Program Parts with Well-Defined

More information

Programming Language Concepts: Lecture 10

Programming Language Concepts: Lecture 10 Programming Language Concepts: Lecture 10 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 10, 16 February 2009 Reflection

More information

Domain-Driven Design Activity

Domain-Driven Design Activity Domain-Driven Design Activity SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Entities and Value Objects are special types of objects

More information

JAVA.LANG.CLASS CLASS

JAVA.LANG.CLASS CLASS JAVA.LANG.CLASS CLASS http://www.tutorialspoint.com/java/lang/java_lang_class.htm Copyright tutorialspoint.com Introduction The java.lang.class class instance represent classes and interfaces in a running

More information

Introflection. Dave Landers BEA Systems, Inc.

Introflection. Dave Landers BEA Systems, Inc. Introflection Dave Landers BEA Systems, Inc. dave.landers@bea.com Agenda What is Introflection? Primary Classes and Objects Loading Classes Creating Objects Invoking Methods Java Beans Proxy What is Introflection?

More information

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about inheritance To understand how

More information

This page intentionally left blank

This page intentionally left blank This page intentionally left blank Absolute Java, Global Edition Table of Contents Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents Chapter 1 Getting Started 1.1 INTRODUCTION

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. 9 Classes and Objects p. 11 Creating Objects p. 12 Static or

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Lecture 4: Extending Classes. Concept

Lecture 4: Extending Classes. Concept Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Memento Prototype Visitor 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Memento 2 Design patterns, Laura Semini, Università

More information

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad Inheritance, type-checking, and method dispatch Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13

More information

Ira R. Forman Nate Forman

Ira R. Forman Nate Forman Ira R. Forman Nate Forman M A N N I N G Java Reflection in Action by Ira R. Forman and Nate Forman Sample Chapter 1 Copyright 2004 Manning Publications contents Chapter 1 A few basics Chapter 2 Accessing

More information

Cloning Enums. Cloning and Enums BIU OOP

Cloning Enums. Cloning and Enums BIU OOP Table of contents 1 Cloning 2 Integer representation Object representation Java Enum Cloning Objective We have an object and we need to make a copy of it. We need to choose if we want a shallow copy or

More information

Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces Chapter 13 Abstract Classes and Interfaces 1 Abstract Classes Abstraction is to extract common behaviors/properties into a higher level in the class hierarch so that they are shared (implemented) by subclasses

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Just before we start Generics Generics are a

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

CN208 Introduction to Computer Programming

CN208 Introduction to Computer Programming CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Inheritance (P1 2006/2007)

Inheritance (P1 2006/2007) Inheritance (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To learn about

More information

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

Intro to Computer Science 2. Inheritance

Intro to Computer Science 2. Inheritance Intro to Computer Science 2 Inheritance Admin Questions? Quizzes Midterm Exam Announcement Inheritance Inheritance Specializing a class Inheritance Just as In science we have inheritance and specialization

More information

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun Announcements Project 1 is out! Due July 15 th. Check the course website. Reminder: the class newsgroup ucb.class.cs61b should

More information

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 P a g e 1 CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 Q1 Describe some Characteristics/Advantages of Java Language? (P#12, 13, 14) 1. Java

More information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018 CSE 331 Software Design and Implementation Lecture 10 Equality and Hashcode Announcements Leah Perlmutter / Summer 2018 Announcements This coming week is the craziest part of the quarter! Quiz 4 due tomorrow

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 31 April 3, 2013 Overriding, Equality, and Casts Announcements HW 09 due Tuesday at midnight More informajon about exam 2 available on Friday Unfinished

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017 COMP 250 Lecture 30 inheritance overriding vs overloading Nov. 17, 2017 1 All dogs are animals. All beagles are dogs. relationships between classes 2 All dogs are animals. All beagles are dogs. relationships

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 32 April 5, 2013 Equality and Hashing When to override: Equality Consider this example public class Point { private final int x; private final int

More information

Objects and Serialization

Objects and Serialization CS193j, Stanford Handout #18 Summer, 2003 Manu Kumar Objects and Serialization Equals boolean equals(object other) vs == For objects, a == b tests if a and b are the same pointer "shallow" semantics boolean

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Prototype 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Prototype Pattern A creational pattern Specify the kinds of objects

More information

CS5233 Components Models and Engineering

CS5233 Components Models and Engineering CS5233 Components Models and Engineering (Komponententechnologien) Master of Science (Informatik) Reflection Seite 1 Java Reflection Reflection Reflection is when you see yourself. Why would you like to

More information

Equality. Michael Ernst. CSE 331 University of Washington

Equality. Michael Ernst. CSE 331 University of Washington Equality Michael Ernst CSE 331 University of Washington Object equality A simple idea Two objects are equal if they have the same value A subtle idea intuition can be misleading Same object/reference,

More information

Java Persistence API (JPA) Entities

Java Persistence API (JPA) Entities Java Persistence API (JPA) Entities JPA Entities JPA Entity is simple (POJO) Java class satisfying requirements of JavaBeans specification Setters and getters must conform to strict form Every entity must

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 April 23, 2014 Overriding and Equality HW 10 has a HARD deadline Announcements You must submit by midnight, April 30 th Demo your project to your

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

CSE 331 Lecture 4. Comparing objects; cloning

CSE 331 Lecture 4. Comparing objects; cloning CSE 331 Lecture 4 Comparing objects; cloning slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Natural ordering,

More information

The Liskov Substitution Principle

The Liskov Substitution Principle Agile Design Principles: The Liskov Substitution Principle Based on Chapter 10 of Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice Hall, 2003 and on Barbara Liskov

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

C12a: The Object Superclass and Selected Methods

C12a: The Object Superclass and Selected Methods CISC 3115 TY3 C12a: The Object Superclass and Selected Methods Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/4/2018 CUNY Brooklyn College 1 Outline The Object class and

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 33 Dec. 1, 2010 Equality Consider this example public class Point {! private final int x; // see note about final*! private final int y;! public Point(int

More information

PIC 20A Number, Autoboxing, and Unboxing

PIC 20A Number, Autoboxing, and Unboxing PIC 20A Number, Autoboxing, and Unboxing Ernest Ryu UCLA Mathematics Last edited: October 27, 2017 Illustrative example Consider the function that can take in any object. public static void printclassandobj

More information

Fundamental Java Methods

Fundamental Java Methods Object-oriented Programming Fundamental Java Methods Fundamental Java Methods These methods are frequently needed in Java classes. You can find a discussion of each one in Java textbooks, such as Big Java.

More information

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

The Java Type System (continued)

The Java Type System (continued) Object-Oriented Design Lecture 5 CSU 370 Fall 2007 (Pucella) Friday, Sep 21, 2007 The Java Type System (continued) The Object Class All classes subclass the Object class. (By default, this is the superclass

More information

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012 Principles of Software Construction: Objects, Design and Concurrency Polymorphism, part 2 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich, and

More information

Advanced programming for Java platform. Introduction

Advanced programming for Java platform. Introduction Advanced programming for Java platform Introduction About course Petr Hnětynka hnetynka@d3s.mff.cuni.cz http://d3s.mff.cuni.cz/teaching/vsjava/ continuation of "Java (NPRG013)" basic knowledge of Java

More information

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information