Java Implementation: Part 3S1 2015 CompSci 230 Software Construction.

Slides:



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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
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.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 10 Classes Continued
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
Java Implementation: Part 3 Software Construction Lecture 8.
Memory Allocation Recall: we use a reference variable to refer to instances of a class. The value in a reference variable is, essentially, a pointer to.
The Java Programming Language
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Java Programming: Program Design Including Data Structures 1 Vectors The class Vector can be used to implement a list Unlike an array, the size of a Vector.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Overriding toString()
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
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.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Classes Dwight Deugo Nesa Matic
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Introduction to C# By: Abir Ghattas Michel Barakat.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
The Object class Object package java.lang Object clone equals hashCode toString aCopy toThis hash string ! yesOrNo.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Lecture 5:Interfaces and Abstract Classes
Intro to Java L. Grewe.
Object-oriented Programming in Java
Continuing Chapter 11 Inheritance and Polymorphism
Java Programming Language
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Sampath Kumar S Assistant Professor, SECE
Chapter 9 Carrano Chapter 10 Small Java
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
CS 240 – Advanced Programming Concepts
Presentation transcript:

Java Implementation: Part 3S CompSci 230 Software Construction

Agenda COMPSCI 230: Impl32  Topics:  Enum Types  Object: a superclass  Memory allocation  An OO description of Java’s type system  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

Enum Types COMPSCI 230: S73  “An enum type is a special data type that enables for [sic] a variable to be a set of predefined constants.  The variable must be equal to one of the values that have been predefined for it.  Common examples include  compass directions (values of NORTH, SOUTH, EAST, and WEST) and  the days of the week.  “Because they are constants, the names of an enum type's fields are in uppercase letters.  “… you define an enum type by using the enum keyword.  For example, you would specify a days-of-the-week enum type as:  “You should use enum types any time you need to represent a fixed set of constants.  That includes natural enum types such as the planets in our solar system and  data sets where you know all possible values at compile time—for example,  the choices on a menu,  command line flags, and so on.” public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Example of enum usage; switch syntax COMPSCI 230: S74 public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; }

Remainder of the EnumTest class COMPSCI 230: Impl35 public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Output:

Importing static members of a class COMPSCI 230: S76  Importing the static members of an enum may significantly reduce “code clutter”, because you won’t have to fully qualify their names.  However a static import may decrease readability, if the reader has trouble figuring out “which class defined this member.” package enumtest; public class EnumTest { enum Day { // note: this is a “nested inner class” SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { (new EnumTest(Day.MONDAY)).tellItLikeItIs(); (new EnumTest(Day.WEDNESDAY)).tellItLikeItIs(); (new EnumTest(Day.FRIDAY)).tellItLikeItIs(); (new EnumTest(Day.SATURDAY)).tellItLikeItIs(); (new EnumTest(Day.SUNDAY)).tellItLikeItIs(); }

Importing static members of a class COMPSCI 230: S77  Importing the static members of an enum may significantly reduce “code clutter”, because you won’t have to fully-qualify their names.  However a static import may decrease readability, if the reader has trouble figuring out “which class defined this member.” package enumtest; import static enumtest.EnumTest.Day.*; public class EnumTest { enum Day { // note: this is a “nested inner class” SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { (new EnumTest(MONDAY)).tellItLikeItIs(); (new EnumTest(WEDNESDAY)).tellItLikeItIs(); (new EnumTest(FRIDAY)).tellItLikeItIs(); (new EnumTest(SATURDAY)).tellItLikeItIs(); (new EnumTest(SUNDAY)).tellItLikeItIs(); }

Switch: semantics COMPSCI 230: S78 public void tellItLikeItIs() { switch (day) { case MONDAY: // Each case is labelled by one (or more) values // in the range of the switch variable (or expression) System.out.println("Mondays are bad."); break; case FRIDAY: // We don’t have to write Day.FRIDAY, because each case // label is a value of the same type as the switch expression. System.out.println("Fridays are better."); break; // Case statements “flow-through” if there’s no break! case SATURDAY: // Note the “flow-through” for this case case SUNDAY: System.out.println("Weekends are best."); break; default: // You’ll get a runtime error if there’s no matching case // but default matches any value of the switch expression System.out.println("Midweek days are so-so."); break; } } } //

Object – this is what your classes extend! COMPSCI 230: S79  When you define a class in Java without specifying what class you’re extending, you’re actually extending the Object class.  The Object as a Superclass lesson briefly discusses six of the methods which your classes inherit from Object.Object as a Superclass Object  protected Object clone() throws CloneNotSupportedException  Creates and returns a copy of this object.  public boolean equals(Object obj)  Indicates whether some other object is “equal to” this one.  protected void finalize() throws Throwable  Called by the garbage collector on an object when garbage collection determines that there are no more references to the object  public final Class getClass()  Returns the runtime class of an object.  public int hashCode()  Returns a hash code value for the object.  public String toString()  Returns a string representation of the object.

Overriding toString() COMPSCI 230: S710  “You should always consider overriding the toString() method in your classes.  “The Object ’s toString() method returns a String representation of the object, which is very useful for debugging.  The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes.”

Overriding equals() COMPSCI 230: S711  The equals() method compares two objects for equality and returns true if they are equal.  The equals() method provided in the Object class uses the identity operator ( == ) to determine whether two objects are equal.  For primitive data types, this gives the correct result.  For objects, however, it does not.  The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.  To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

Example: overriding equals() COMPSCI 230: S712 public class Book { String Title; String Author; String Publisher; String Year; String ISBN;... public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals(((Book) obj).getISBN()); else return false; }... }

Example: overriding equals() COMPSCI 230: S713 public class Book { String Title; String Author; String Publisher; String Year; String // This annotation suppresses error messages from the // Java compiler, and it improves readability. public boolean equals(Object obj) { // Note: the same signature // as Object.equals(), but with a different implementation if (obj instanceof Book) return ISBN.equals(((Book) obj).getISBN()); else return false; }...

Example: testing an overridden equals() COMPSCI 230: S714 public static void main(String[] args){ Book firstBook = new Book(" "); Book secondBook = new Book(" "); if (firstBook.equals(secondBook)) { System.out.println("equivalent objects"); } else { System.out.println("non-equivalent objects"); } if (firstBook == secondBook){ System.out.println("two references to the same object"); } else { System.out.println("references to different objects"); }

Memory Allocation COMPSCI 230: S715  Recall: we use a reference variable to refer to instances of a class.  The value in a reference variable is, essentially, a pointer to an object.  A special value ( null ) indicates that there is no object corresponding to this reference.  The runtime system (the JVM) interprets a reference value as an index into a heap.  The new operator allocates sufficient memory on the heap to store all of the fields of an object of the requested type.  Formally: the range of allowable values for a reference variable is its reference type.  The reference type of o1 is Object. This means it can point to any instance of Object, or to any instance of any subclass of Object.  Java also has primitive variables.  These have a primitive type, such as int.  They don’t refer to objects.  In Java, a reference type is a static type, and a primitive type is also a static type.  Static types are determined by a static analysis of the program text.  A reference variable has a dynamic type, which is determined at runtime by the type of the object it is referring to. 0xfe :Ball -class :Class = Ball xPos :int = 10 yPos :int = 20 Color :Java.awt.Color = RED int i = 20; Ball b1 = new Ball( 10, i, Color.RED ); Object o1 = b1; :StackFrame i :int = 20 b1 :Ball = 0xfe o1 :Object = 0xfe refersTo static types dynamic type

A model of Java’s type system (for reference) COMPSCI 230: S716 Source: Kollman, R. and Gogolla, M., “Capturing Dynamic Program Behaviour with UML Collaboration Diagrams”, Proc. CSMR, 2001.

Review COMPSCI 230: S717  Topics in this set of slides:  Enum types  Object.toString(), Object.equals()  Memory allocation  An overview of Java’s type system  End of Theme A: The OO Programming Paradigm  We took a top-down approach: use-case analysis  class design  implementation.  You learned the fundamentals of OO design theory  You are starting to understand type systems  You have a basic understanding of Java development (JDK, Eclipse) and Java runtime (JRE).  You understand the difference between the static type of a reference variable (defined by its declaration) and its dynamic type (defined by its current value)  You have a basic proficiency in program analysis, OOD, and Java implementation  You are able to “learn more”, if necessary, by reading, thinking, and experimenting.