30-Jun-15 More about Classes. 2 Composition The most common way to use one class within another is composition—just have a variable of that type Examples:

Slides:



Advertisements
Similar presentations
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Generic programming in Java
Inheritance Inheritance Reserved word protected Reserved word super
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
ITEC200 – Week03 Inheritance and Class Hierarchies.
© The McGraw-Hill Companies, 2006 Chapter 8 Extending classes with inheritance.
Road Map Introduction to object oriented programming. Classes
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,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
15-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
Subclasses 17-Apr-17.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Subclasses. Inheritance class Animal { int row, column; // will be inherited private Model model; // private prevents inheritance Animal( ) {... } //
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
28-Jun-15 Everything You Ever Wanted To Know About Java O-O.
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.
Abstract Classes and Interfaces
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Object oriented design in Java (useful revision for final exam)
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
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.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Best Practices. Contents Bad Practices Good Practices.
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.
Programming in Java CSCI-2220 Object Oriented Programming.
Types in programming languages1 What are types, and why do we need them?
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
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,
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
More about Classes 31-May-18.
Polymorphism 11-Nov-18.
Polymorphism 15-Nov-18.
Java Programming Language
Subclasses 29-Dec-18.
More about Classes 24-Feb-19.
Chapter 9 Carrano Chapter 10 Small Java
Polymorphism 21-Apr-19.
Subclasses 5/1/ Dec-04 subclasses.ppt.
More about Classes 3-May-19.
Presentation transcript:

30-Jun-15 More about Classes

2 Composition The most common way to use one class within another is composition—just have a variable of that type Examples: class LunarLanderGame { LunarLander lander = new LunarLander();... class MaxPlayer { String name; // String is a class Game game; // Game is a class Composition is suitable when one class is composed of objects from another class, or needs frequent reference to objects of another class

3 Composition vs. Inheritance Inheritance is appropriate when one class is a special case of another class Example 1: class Animal {... } class Dog extends Animal {... } class Cat extends Animal {... } Example 2: class Player {... } class ComputerPlayer extends Player {... } class HumanPlayer extends Player {... } Use inheritance only when one class clearly specializes another class (and should have all the features of that superclass) Use composition in all other cases

4 Inheritance class Animal { int row, column; // will be inherited private Model model; // inherited but inaccessible Animal( ) {... } // cannot be inherited void move(int direction) {... } // will be inherited } class Rabbit extends Animal { // inherits row, column, move, but not constructor // model really is inherited, but you can’t access it int distanceToEdge; // new variable, not inherited int hideBehindBush( ) {... } // new method, not inherited }

5 Assignment A member of a subclass is a member of the original class; a rabbit is an animal Animal animalBehindBush; Rabbit myRabbit;... animalBehindBush = myRabbit; // perfectly legal myRabbit = animalBehindBush; // not legal myRabbit = (Rabbit)animalBehindBush; // legal syntax, but requires a runtime check

6 Assignment II animalBehindBush = myRabbit; is legal--but why? int NUMBER_OF_ANIMALS = 8; Animal animals[ ] = new Animal[NUMBER_OF_ANIMALS]; animals[0] = new Rabbit(); animals[1] = new Seagull(); animals[2] = new Snail();... for (int i = 0; i < NUMBER_OF_ANIMALS; i++) animals[i].move(); // legal if defined in Animal

7 Assignment III From previous slide: for (int i = 0; i < NUMBER_OR_ANIMALS; i++) animals[i].allowMove(); // legal if defined in Animal But: for (int i = 0; i < NUMBER_OR_ANIMALS; i++) { if (animals[i] instanceof Rabbit) { ((Rabbit)animals[i]).tryToHide(); } } Here, tryToHide() is defined only for rabbits We must check whether animals[i] is a rabbit We must cast animals[i] to Rabbit before Java will allow us to call a method that does not apply to all Animal s After the if test, you might think Java “knows” that animals[i] is a Rabbit —but it doesn’t

8 Arrays of Objects When you declare an array, you must specify the type of its elements: Animal animals[ ]; However, Object is a type, so you can say: Object things[ ]; // declaration things = new Object[100]; // definition You can put any Object in this array: things[0] = new Fox(); But (before Java 5) you cannot do this: things[1] = 5; // why not?

9 Wrappers Each kind of primitive has a corresponding wrapper (or envelope) object: byte Byte short Short int Integer (not Int ) long Long char Character (not Char ) boolean Boolean float Float double Double

10 Wrapper constructors Each kind of wrapper has at least one constructor: Byte byteWrapper =new Byte(byte value ) Short shortWrapper =new Short(short value ) Integer intWrapper =new Integer(int value ) Long longWrapper =new Long(long value ) Character charWrapper =new Character(char value ) Boolean booleanWrapper =new Boolean(boolean value ) Float floatWrapper =new Float(float value ) Double doubleWrapper =new Double(double value )

11 More wrapper constructors Every wrapper type except Character has a constructor that takes a String as an argument Example: Double d = new Double("3.1416"); Example: Boolean b = new Boolean("true"); The constructors for the numeric types can throw a NumberFormatException : Example: Integer i = new Integer("Hello");

12 Wrapper “deconstructors” You can retrieve the values from wrapper objects: byte by = byteWrapper.byteValue(); short s = shortWrapper.shortValue(); int i = intWrapper.intValue(); long l = longWrapper.longValue(); char c = charWrapper.charValue(); boolean bo = booleanWrapper.booleanValue(); float f = floatWrapper.floatValue(); double d = doubleWrapper.doubleValue();

13 Additional wrapper methods Wrapper classes have other interesting features variables: Integer.MAX_VALUE = methods: Integer.toHexString(number) anyType.toString();

14 Back to arrays Why bother with wrappers? Object[ ] things = new Object[100]; Prior to Java 5, you cannot do this: things[1] = 5; But you could do this: things[1] = new Integer(5); You couldn’t do this: int number = things[1]; But you could do this: int number = ((Integer)things[1]).intValue();

15 Auto-boxing and auto-unboxing Since version 5, Java will automatically box (wrap) primitives when necessary, and unbox (unwrap) wrapped primitives when necessary You can now do the following (where things is an array of Object ) : things[1] = 5; instead of things[1] = new Integer(5); int number = (Integer)things[1]; instead of int number = ((Integer)things[1]).intValue(); but not int number = (int)things[1];

16 equals and other methods Some methods, such as equals, take an Object parameter Example: if (myString.equals("abc")) {... } JUnit's assertEquals( expected, actual ) also takes objects as arguments Auto boxing and unboxing, while convenient, can lead to some strange problems: Integer foo = new Integer(5); Integer bar = new Integer(5); Now: foo == 5 is true bar == 5 is true foo.equals(bar) is true foo.equals(5) is true foo == bar is false

17 Types and values A variable has both a type and a value Consider Animal animal; The type of variable animal is Animal The type of a variable never changes The syntax checker can only know about the type The value of animal might sometimes be a rabbit and at other times be a fox Messages such as animal.run() are sent to the value The value (object) determines which method to use

18 Sending messages Java must ensure that every message is legal That is, the object receiving the message must have a corresponding method But when the Java compiler checks syntax, it can’t know what the value of a variable will be; it has to depend on the type of the variable If the variable is of type T, then either Class T must define an appropriate method, or Class T must inherit an appropriate method from a superclass, or Class T must implement an interface that declares an appropriate method

19 Overriding methods class Animal { int decideMove( ) { return Model.STAY; } } class Rabbit extends Animal { // override decideMove int decideMove( ) { // same signature return random(Model.MIN_DIRECTION, Model.MAX_DIRECTION); } }

20 Overriding methods II When you override a method: You must have the exact same signature Otherwise you are just overloading the method, and both versions of the method are available When you override a method, you cannot make it more private In this example, Animal defines a method Every subclass of Animal must inherit that method, including subclasses of subclasses Making a method more private would defeat inheritance

21 Some methods cannot be overridden class Animal { final boolean canMove(int direction) {... } } class Rabbit extends Animal { // inherits but cannot override canMove(int) }

22 Some variables cannot be shadowed class BorderLayout { public static final String NORTH = "North"; If you were to create a subclass of BorderLayout, you would not be able to redefine NORTH

23 Some classes cannot be extended final class StringContent {... } When an entire class is made final, it cannot be extended (subclassed) Making a class final allows some extra optimizations Very few Java-supplied classes are final final classes are a bad idea in general—programs almost always get used in ways that were not foreseen by their authors

24 Some classes cannot be instantiated In the AWT, TextField extends TextComponent, and TextComponent extends Component You can create (instantiate) a TextField, but you cannot directly create either a TextComponent or a Component What is it that prevents you from doing so? Component is an abstract class, and abstract classes cannot be instantiated TextComponent has an explicit constructor, but it is private

25 Some objects cannot be altered An immutable object is one that cannot be changed once it has been created String s are immutable objects It’s easy to make an object immutable: Make all its fields private Provide no methods that change the object

26 You can always be more specific Rule: Design subclasses so they may be used anywhere their superclasses may be used If a Rabbit is an Animal, you should be able to use a Rabbit object anywhere that an Animal object is expected

27 Don’t change the superclass The Liskov Substitution Principle: Methods that use references to base classes must be able to use objects of derived classes without knowing it If you introduce a Deer class, you should not have to make any changes to code that uses an Animal If you do have to change code, your Animal class was poorly designed

28 Extend, don’t modify The Open-Closed Principle: Software entities (classes, modules, methods, and so forth) should be open for extension but closed for modification You should design classes that can be extended You should never have to modify a class in order to extend it

29 Related style rules, I Rule: Define small classes and small methods. Smaller classes and methods are easier to write, understand, debug, and use Smaller classes are more focused--they do only one thing This makes them easier to extend

30 Related style rules, II Rule: Build classes from primitives and Java-defined classes; avoid dependence on program-specific classes The less your class depends on others, the less it has to be “fixed” when the others change If your class is stand-alone, maybe it can be used in some future program Dependencies are shown in BlueJ with dotted arrows; the fewer of these you have, the better

31 Related style rules, III Rule: Make all fields private. Private fields are controlled by your class; no other class can snoop at them or meddle with them This means you can change them if necessary You can provide setter and getter methods (to set and get field values) when you think it is appropriate to give this kind of access Even if you provide setter and getter methods, you maintain a measure of control

32 Related style rules, IV Rule: Use polymorphism instead of instanceof Bad: class Animal { void move() { if (this instanceof Rabbit) {... } else if (this instanceof Fox) {... } } } Good: class Rabbit extends Animal { void move() {... } } class Fox extends Animal { void move() {... } }

33 The End