Object-oriented Programming in Java. What is OOP?  The goal is (subtype) polymorphism  Achieved by Classes (user-defined types) Classes (user-defined.

Slides:



Advertisements
Similar presentations
Classes And Objects II. Recall the LightSwitch Class class LightSwitch { boolean on = true; boolean isOn() { return on; } void switch() { on = !on; }
Advertisements

STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
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.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
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.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism.
Topic 4 Inheritance.
Types in programming languages1 What are types, and why do we need them?
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance and Access Control CS 162 (Summer 2009)
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…..
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance ndex.html ndex.htmland “Java.
CSC142 NN 1 CSC 142 Overriding methods from the Object class: equals, toString.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
100e Hosted by vhs © Don Link, Indian Creek School, 2004 Jeopardy.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Modern Programming Tools And Techniques-I
Object-oriented Programming in Java
Inheritance and Polymorphism
Lecture 17: Polymorphism (Part II)
Overloading and Constructors
null, true, and false are also reserved.
Inheritance.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Generic Classes and Methods
Overriding methods from the Object class: equals, toString
Lecture 18: Polymorphism (Part II)
Advanced Inheritance Concepts
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Subtype Substitution Principle
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

Object-oriented Programming in Java

What is OOP?  The goal is (subtype) polymorphism  Achieved by Classes (user-defined types) Classes (user-defined types) Inheritance (is-a, substitutability) Inheritance (is-a, substitutability) Dynamic Function Binding Dynamic Function Binding Function to run is bound according to the dynamic type of the objectFunction to run is bound according to the dynamic type of the object

Upcasting  Storing a reference to a subtype in a supertype variable  Makes sense because of the is-a relationship  Allows any subtype object to be used in a context expecting a supertype object  Employee e = new SalariedEmployee();

The instanceof operator  Returns true if the left operand is the same type or a subtype of the right operand new HourlyEmployee() instanceof Employee is true new HourlyEmployee() instanceof Employee is true  Often used before downcasting To avoid an exception To avoid an exception

Polymorphism  Dynamic variation of behavior  According to an object’s dynamic type Calls the function corresponding to the type the reference indicates at the moment Calls the function corresponding to the type the reference indicates at the moment Invisibly to the program Invisibly to the program  Employee e = new HourlyEmployee(); e.computePay(); e = new SalariedEmployee(); e.computePay(); // A different function!  Example: Figure 2

Benefits of OOP  High degree of separation among components Low coupling Low coupling  Insulates components from changes in other components  Example: payroll program Uses the Employee interface Uses the Employee interface The dynamic types are invisible The dynamic types are invisible

Downcasting  When an object must be interpreted as a subtype When extracting from a collection, for example When extracting from a collection, for example  Must use with care The object may not be the type you’re expecting The object may not be the type you’re expecting Checked at runtime Checked at runtime  Examples: Figures 4, 5

Abstract Classes  Not meant to be instantiated  Define an interface  Also define part of the implementation  Subclasses complete the implementation  abstract keyword Both for classes and methods Both for classes and methods

java.lang.Object  The Mother of all Classes All objects are subtypes of Object All objects are subtypes of Object  Object methods: int hashCode( ); int hashCode( ); boolean equals(Object); boolean equals(Object); String toString( ); String toString( ); Among others… Among others…

Object.toString  Provides a String representation of an object  Prints the class name and the hashCode  Should override

Object.equals(Object)  Used for a value-based equality test  Override carefully: Test == this first Test == this first if true, return trueif true, return true Test instanceof TheClass Test instanceof TheClass if false, return falseif false, return false Then check all the fields Then check all the fields Use equals() recursively for object fieldsUse equals() recursively for object fields Can super.equals() for inherited fieldsCan super.equals() for inherited fields Examples: ColorPoint (next slide) and SuperEquals.java Examples: ColorPoint (next slide) and SuperEquals.java  Always override hashCode() if you override equals()

ColorPoint public boolean equals(Object other) { if (this == other) return true; else if (!(other instanceof ColorPoint)) return false; ColorPoint p = (ColorPoint) other; return (super.equals(p) && p.color.equals(this.color)); } int x, yColor color Instance variables in parent class, Point: Instance variable in child class, ColorPoint:

Floating-point Fields  Don’t compare for equality with ==! Has to do with special values (NaN, etc.) Has to do with special values (NaN, etc.)  Convert floats to int with Float.floatToIntBits  Convert doubles to long with Double.doubleToLongBits  Compare the resulting integers with ==

hashCode  Used to associate an object with an int  Used in hash tables and other containers  Should be “as unique as possible”  Rules: Boolean: (f ? 0 : 1) Boolean: (f ? 0 : 1) byte, char, or short: (int) f byte, char, or short: (int) f Long: (int)(f ^ (f>>>32)) Long: (int)(f ^ (f>>>32)) Float: Float.floatToIntBits(f) Float: Float.floatToIntBits(f) Double: Double.doubleToLongBits(f) Double: Double.doubleToLongBits(f) Combine with prime numbers: h = 37*f1; h = 37*h;… Combine with prime numbers: h = 37*f1; h = 37*h;… Objects: combine their hashcodes (see pp ) Objects: combine their hashcodes (see pp )