Java Implementation: Part 3 Software Construction Lecture 8.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Lecture 5: Interfaces.
Java Implementation, Part 2S CompSci 230 Software Construction.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Java Implementation: Part 2 Version 1.4 of : rearranged slides CompSci 230 Software Construction.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
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.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Java Implementation Software Construction Lecture 6.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Packages & Binding CompSci 230 S Software Design and Construction.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Java Implementation: Part 4 Software Construction Lecture 9.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
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.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
The Object-Oriented Thought Process Chapter 03
OOP: Encapsulation &Abstraction
CompSci 230 S Programming Techniques
Inheritance and Polymorphism
Object Oriented Programming
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Java Inheritance.
Presentation transcript:

Java Implementation: Part 3 Software Construction Lecture 8

Agenda 2  Topics:  Enum Types  Memory allocation: another view of Java’s type system  Object Identity, Assignment, Equality, and Copying  The Object class  Overriding equals() and toString()  Cloning  Nested Classes  What and Why  Reading, in The Java Tutorials:The Java Tutorials  Enum Types and Nested Classes pages, in the Classes and Objects Lesson. Enum TypesNested ClassesClasses and Objects  Object as a Superclass page, in the Interface and Inheritance Lesson. Object as a SuperclassInterface and Inheritance  Equality, Relational, and Conditional Operators page, in the Language Basics Lesson. Equality, Relational, and Conditional OperatorsLanguage Basics  For reference:  The 3 things you should know about hashCode(), Eclipse Source Developer, available 20 March The 3 things you should know about hashCode()

Learning objectives for this week 3  Students will be competent at implementing OO designs in Java  Interfaces, reference data types, abstract classes, intro to generics  Visibility, packages, static & dynamic typing, conversion & casting  Enums, memory allocation, object identity & assignment & equality & cloning, nested classes  The lectures will give you the basic “theory”, but they won’t give you a “working understanding” – you have to do the hard-yards of putting these ideas into practice.  You won’t even understand the theory, if you listen passively to lectures. I’ll try to help you “learn how to learn” from the Java tutorials.  You’ll get many chances to develop your understanding in your lab assignments for this course.

Keywords for Control of Inheritance 4  Every subclass will  inherit all superclass members that are declared as public or protected.  By contrast,  private members are not inherited (but may be accessible through super.)  The default visibility is “package-private” – inherited by subclasses within the same package, but not inherited by subclasses that are declared outside the package.  No subclass can  override static methods, or  override final methods.  Any subclass may  add new members (= fields or methods), or  override any non- static, non- final method in the superclass.  We say a method is overridden in a subclass, if any of its superclasses has a method of the same signature (= name, plus the number and types of parameters) and return type.  Note that overriding does not absolutely prevent access. A reference to the superclass member is still possible (e.g. with super ) if this member is visible.

Statically or Dynamically typed  Programming languages generally offer some sort of type system, and can be described as being either statically typed or dynamically typed  With a statically typed language, compile-time checks are carried out to determine whether variable usage is valid.  In a dynamically typed language, variables are not associated with a type and are simply names that can be assigned arbitrary values. 5 Java int x = 10; x = "Hello"; Python x = 10; x = "Hello";

Java - a statically typed language  Every variable name is bound  to a static type (at compile time, by means of a data declaration), and  either to a dynamic type or null, depending on its current value  The type restricts the values that can be bound to this variable.  int x = 2.3;  The type also restricts the messages that can be sent using the variable.  int x = 2; (Vector) x.add(0x37);  Restrictions are checked at compile-time.  The compiler will not issue code if it detects a violation.  Java is a “type-safe” language: its compile-time checking restricts the amount of damage that can be done by careless or malicious programmers. 6 Ball b1 = new Ball(...); Ball b2 = null; static type dynamic type

Static Typing Restrictions  A reference variable of static type T can refer to an instance of class T or to an instance of any of T’s subclasses.  A type is a restriction on the values that can be taken by a variable, and a subclass is a stricter restriction – so there can be no type error when a value in a subtype of T is assigned to a variable of type T.  Through a reference variable of static type T, the set of messages that can be sent using that variable are the methods defined by class T and its superclasses.  This typing rule allows inherited methods to be accessed via T, in contexts where the names of these methods are visible.  There might be many subclasses of T, each defining different methods with the same name – so T can’t be used to refer to any of these subclass methods.  Recall: a variable’s static type is fixed at compile time,  but its dynamic type may vary at run-time. 7

Example: Static Binding of Instance Variables 8 class Base { public int x = 10; } public class Derived extends Base { public int y = 20; } //Case 1: Base b1 = new Base(); System.out.println("b1.x=" + b1.x) ; b1.x=10 //Case 2: Derived b2 = new Derived(); System.out.println("b2.x=" + b2.x); System.out.println("b2.y=" + b2.y); //Case 3: Base b3 = new Derived(); System.out.println("b3.x=" + b3.x); // System.out.println("b3.y=" + b3.y); Instance variable x in Base. There is no y declared in the Base class – this won’t compile! b1.x=10 b2.y=20 b3 has static type Base, and dynamic type Derived. b2 has static type Derived, and dynamic type Derived. b3.x=10 Instance variable x in Derived: inherited from Base

Static Binding – Hiding a Field 9  “Within a class, a field that has the same name as a field in the superclass hides the superclass's field,  even if their types are different.  “Within the subclass, the field in the superclass cannot be referenced by its simple name.  “Instead, the field must be accessed through super, which is covered in the next section.  “Generally speaking, we don't recommend hiding fields as it makes code difficult to read.” [The Java Tutorials] class Base { public int x = 10; } public class Derived extends Base { public String x = “20”; } Base b3 = new Derived(); System.out.println("b3.x=" + b3.x);

Review: Fields & Variables 10  The Java Tutorials makes a careful distinction between fields and variables.  Not many programmers use these terms carefully.  You won’t understand the Java Tutorials, in full technical detail, unless you understand its definitions!  In the Variables page of the Language Basics Lesson:VariablesLanguage Basics  “Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in ‘non-static fields’, … also known as instance variables …  “Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.  “Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. … There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.  “Parameters … The important thing to remember is that parameters are always classified as ‘variables’ not ‘fields’. … [In addition to methods, ] other parameter- accepting constructs … [include] constructors and exception handlers …”

Dynamic Binding 11  If a method is overridden, then the compiler may not be able to resolve a reference to that method.  The runtime search for an overridden method begins with the dynamic type.  If this type doesn’t implement the method (i.e. it neither introduces nor overrides the method), then the search progresses up the hierarchy, until the method is found.  Static type-checking ensures that an implementation will be found (unless the class was changed, and re-compiled, after the type-check.) Derived b2 = new Derived(); Base b3 = new Derived(); b2.f(); class Base { public void f() {... } public void g() {... } } public class Derived extends Base { public void g() {... } public void h() {... } } Dynamic type b2.g(); Inherited: invoke f() in Base Overridden: invoke g() in Derived b2.h(); Introduced: invoke h() in Derived

Dynamic Binding 12  If a method is overridden, then the compiler may not be able to resolve a reference to that method.  The runtime search for an overridden method begins with the dynamic type.  If this type doesn’t implement the method (i.e. it neither introduces nor overrides the method), then the search progresses up the hierarchy, until the method is found.  Static type-checking will ensure that an implementation will be found -- unless the class was changed, and re-compiled, after the type-check! Derived b2 = new Derived(); Base b3 = new Derived(); b3.f(); class Base { public void f() {... } public void g() {... } } public class Derived extends Base { public void g() {... } public void h() {... } } Dynamic type b3.g(); b3.h(); Inherited: invoke f() in Base Overridden: invoke g() in Derived Out of scope: compile-time error

Conversions of Primitive Types  Widening conversions  Wider assignment, e.g. int i = 2; float x = i;  Wider casting, e.g. int i = 2; double d = (double) i;  Explicitly casting can make your code more readable  Narrowing conversions  Narrow assignment  a compile-time error! float f = 2.0; int i = f;  Narrow casting  a loss of information! float f = 2.0; int i = (int) f; 13 Wider type Casting needed

Object Type Conversions 14  Widening conversions  Wider object reference assignment conversion (allowed)  Wider object reference casting (optional: improves readability) Base b = new Base(); Derived d = new Derived(); Base b1, b2; System.out.println(d.y); b1 = d; //System.out.println(b1.y); Base Derived Wider type b2 = (Base) d; //System.out.println(b2.y); Assignment conversion - OK But no access to fields in Derived! Widening with explicit cast - Better Still no access to fields in Derived!

Object Types 15  Narrowing conversions  Narrow object reference assignment – Compile-time error!  Narrow object reference casting – no compilatation error, but…  The cast may throw an error at run-time, to avoid assigning an out-of-range value! BasePerson DerivedStudent Wider type Base b = new Base(); Derived d = new Derived(); Derived d1, d2, d3; d1 = b; d2 = (Derived) b; A compile-time error Compile-time OK, Run-time ERROR b is an instance of class Base, not Derived! java.lang.ClassCastException: Base Base d_as_b = new Derived(); d3 = (Derived) d_as_b; Compile-time OK: Derived is a narrower (more refined) type Run-time OK: d_as_b is an instance of Derived

Overriding, hiding, and overloading methods 16  “An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.”  “If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.  “The distinction between hiding and overriding has important implications.  The version of the overridden method that gets invoked is the one in the subclass.  The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.”  “Overloaded methods are differentiated by the number and the type of the arguments passed into the method.”  “The compiler does not consider return type when differentiating methods, so you cannot declare two methods [in the same class] with the same signature even if they have a different return type.  “Note: Overloaded methods should be used sparingly, as they can make code much less readable.”

Review 17  Topics:  Four visibility keywords:  How do they affect the scope of access to a field or method?  Packages:  Why and how?  What conventions should you follow?  Static and dynamic typing:  When do they occur?  What is “type-safety”?  Object conversion, casting:  What is allowed at compile-time?  What might happen at run-time?  How do they affect readability?