Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Java Implementation: Part 3 Software Construction Lecture 8.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Software Development
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Subtype Polymorphism, Subtyping vs
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Overview of C++ Polymorphism
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
1 Lecture 23: Dynamic Binding (Section ) CSCI 431 Programming Languages Fall 2002 A compilation of material developed by Felix Hernandez-Campos.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Object-Oriented Programming
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Subtype Polymorphism, Subtyping vs
Overview of C++ Polymorphism
Advanced Inheritance Concepts
Presentation transcript:

Overview of Java (continue)

Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve added this class on or after Jan 26, you need to contact me so that I set up your repository Always check the Announcements page! 2 Spring 15 CSCI 2600, A Milanova

Outline Overview of Java, continued Last time we covered Model for variables Type safety Compilation vs. interpretation This lecture A bit more on type safety Reflection Subtype polymorphism; classes and interfaces Spring 15 CSCI 2600, A Milanova 3

A Bit More on Type Safety Type safety: no operation is ever applied on an object that does not support the operation E.g., a+b where a and b are 2DPoint s will be rejected as + cannot be applied on 2DPoint s E.g., a.substring(0,10) cannot be applied if a is an int Type safety prevents runtime errors --- if an operation is applied on an object of the wrong type, this almost certainly leads to errors! Spring 15 CSCI 2600, A Milanova 4

Type Safety Java ensures type safety with a combination of compile-time (static) and runtime checks Compiler checks and rejects a large number of programs. E.g., String s = 1 is rejected, String s = new Integer(1) is rejected Some checks are left for runtime. Can you think of a reason why? E.g., at B b = (B) x; the Java runtime checks if x refers to a B, and throws an Exception if it doesn’t Spring 15 CSCI 2600, A Milanova 5

Type Safety and Exceptions Exceptions are good! They prevent application of operations on the wrong type Object x = new A(); B q = (B) x; // ClassCastException // because A is not a B int case2 = q.foo(1); The exception prevents execution from reaching q.foo(1) and applying foo(1) on an object (A) that does not have a foo(int) 6

Type Safety Java is type safe while C++ is type unsafe Java forbids a larger set of errors E.g., in Java, a[i] will throw an Exception if i is out of the bounds of array a. In C++, a[i] can access arbitrary memory, which can lead to insidious errors! Thus, it is easier to write correct programs in Java, because the language itself prevent so many errors 7

Reflection Roughly, the ability of the program to execute code synthesized at runtime. Also, the ability to query metadata about classes E.g., in JavaScript: eval(string) executes string. string can be arbitrary code synthesized at runtime Java supports reflection. C++ does not 8

Reflective Object Creation Standard way to instantiate an object: new Another way: reflective object creation: // First, translate the String argument (the first command-line // argument in this case) into a Class object: Class cl = Class.forName(args[0]); // Next, instantiate the class: Set s = (Set) cl.newInstance(); The class of the object created here is not known until runtime! We can specify a java.util.HashSet or a java.util.TreeSet or other at the command line 9

Reflection Reflection is a very powerful technique Sometimes, we do need to use classes unknown at compile time Important design patterns use reflection. More on this later in our class Disadvantages Awkward code Slows program Prevents optimizations Spring 15 CSCI 2600, A Milanova 10

Reflection Avoid using reflection If you have to use, use only object creation, and access the object through an interface, as shown here: // Translate the string into a Class object: Class cl = Class.forName(str); // Instantiate the class: Set s = (Set) cl.newInstance(); // Access the Set through its interface methods s.add(something) // Set is an Interface defined in the Java library 11

Classes and Inheritance Base class and derived class E.g., in C++: class queue : public list queue is the derived class, list is the base class In Java: class queue extends list In Java we say superclass and subclass Other terms are parent class and child class By deriving new classes programmer forms class hierarchies 12

13 Subtype Polymorphism Subtyping and subtype polymorphism – the ability to use a subclass where a superclass is expected Thus, dynamic method binding Advantages? Disadvantages? In C++ static binding is default, dynamic binding is specified with keyword virtual In Java dynamic binding is default, static binding is specified with final

14 Example: Application Draws Shapes on Screen abstract class Shape { public void draw(); } class Circle extends Shape { … } class Square extends Shape { … } void DrawAll(Shape[] list) { for (int i=0; i < list.length; i++) { Shape s = list[i]; s.draw(); } Dynamic dispatch: Call s.draw() resolves at runtime. It can resolve to Circle.draw() or to Square.draw() depending on what object s refers to. In the static context, we only know of Shape.

Dynamic Method Binding Dynamic method binding (dynamic dispatch) is the ability to invoke a new, refined method, in a context, where an earlier version is expected Example on previous slide: s.draw() binds dynamically (i.e., at runtime) to one of Circle.draw() or Square.draw() Spring 15 CSCI 2600, A Milanova 15

Subtype Polymorphism Polymorphism is an important concept in programming languages and software Polymorphism means “many forms” Example on slide 14. DrawAll is polymorphic because it works with many concrete types, Circle, Square, Triangle It’s subtype polymorphism because these concrete types are related: they are all “subtypes” of Shape 16

Benefits of Subtype Polymorphism Enables extensibility and reuse! In our example, we can extend the Shape hierarchy without modifying DrawAll We can reuse Shape and DrawAll Subtype polymorphism enables the Open/closed principle (credited to Bertrand Meyer) Software entities (classes, modules) should be open for extension but closed for modification In other words, it’s easy to extend the code with additional functionality 17 Spring 15 CSCI 2600, A Milanova

18 Benefits of Subtype Polymorphism abstract class Shape { public void draw(); } class Circle extends Shape { … } class Square extends Shape { … } class Triangle extends Shape { … } Makes it very easy to extend with a Triangle! The Java code requires no changes in DrawAll! It would have been very hard to extend analogous C code! Spring 15 CSCI 2600, A Milanova

“Science” of software design teaches Design Patterns. A lot on Design patterns later in our class Design patterns promote design for extensibility and reuse. Maintainable software Nearly all design patterns make use of subtype polymorphism! Spring 15 CSCI 2600, A Milanova 19 Benefits of Subtype Polymorphism

20 Some Differences C++ vs. Java Access control modifiers – public, private, and others What portion of the class is visible to users ? Public, protected or private visibility Java: Has package is default; protected is slightly different from C++ C++: Has friend classes and functions Visibility of superclass members C++: a subclass can restrict visibility of superclass members Java: a subclass can neither increase nor restrict visibility of superclass members Inheritance C++ allows for multiple inheritance Java allows single class inheritance & multiple interface “inheritance” E.g., class B extends A implements I, J, K… Spring 15 CSCI 2600, A Milanova

Subclassing in Java Subtype polymorphism is achieved by subclassing There is a subtle difference between subtyping and subclassing. More on this later! Typical subclassing in good Java code: Subclass an abstract class In our example, Shape is abstract, Circle and Square are concrete subclasses Implement an interface Shape is an interface and Circle and Square implement the interface (next slide) 21

22 An Interface interface Shape { public void draw(); } class Circle implements Shape { // must implement void draw() public void draw() { … } … // other methods } class Square implements Shape { public void draw() { … } … // other methods } Spring 15 CSCI 2600, A Milanova

Subclassing in Java Rarely we subclass a concrete class. Subtle issues arise In homework 0, we had the choice to inherit BallContainer (reuse through inheritance), or to include BallContainer (reuse through composition) Composition is almost always the better choice! Spring 15 CSCI 2600, A Milanova 23

Abstract Classes vs. Interfaces in Java Two mechanisms to define abstract supertypes Abstract classes and Interfaces Abstract class Can contain implementation for some methods Has at least one empty method A good choice when the concrete subclasses share implementation 24 Spring 15 CSCI 2600, A Milanova

Abstract Classes vs. Interfaces in Java Interface Cannot contain any implementation, just signatures! E.g., MapEntry from the Java library: interface MapEntry { boolean equals(Object o); K getKey(); V getValue(); int hashCode(); V setValue(V value); } 25 Spring 15 CSCI 2600, A Milanova This is a generic interface, K and V are type parameters. (Like C++ templates) There is no implementation, all methods are just signatures.

Abstract Classes vs. Interfaces public abstract class AbstractMapEntry implements Map.Entry { public abstract K getKey(); public abstract V getValue(); // Implements public boolean equals(Object o) { if (o == this) // much more here… } … 26

On Tuesday Reasoning about code and Hoare Logic Spring 15 CSCI 2600, A Milanova 27