Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Generics and the ArrayList Class
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Generics and The ArrayList Class
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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.
Java Implementation: Part 3 Software Construction Lecture 8.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
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.
Types in programming languages1 What are types, and why do we need them?
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…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Introduction to Object-Oriented Programming Lesson 2.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Java Generics.
Inheritance and Polymorphism
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Java – Inheritance.
Presentation transcript:

Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition is the class, not the algorithm.” – Grady Booch

©SoftMoore ConsultingSlide 2 The Implicit Reference “ this ” Each object of a class maintains its own copy of the fields, but all objects share a single set of methods. Example BankAccount acct = new BankAccount(); acct.deposit(500); Every method contains an implicit argument named “ this ” that references the object invoking the method. public void deposit(/* BankAccount this, */ int amount); In the definition of a method, using the name of a field references the field of the object for which the method was invoked; i.e., the object referenced by “ this ”

©SoftMoore ConsultingSlide 3 Examples: Using the Reference “ this ” Example 1: implicit use of this public void deposit(int amount) { balance = balance + amount; } Example 2: explicit use of this public BankAccount(int accountId) { this.accountId = accountId; }

©SoftMoore ConsultingSlide 4 Constructor this() Syntax public class Circle { private double area = 0.0; private double radius = 0.0; public Circle(double radius) { this.radius = radius; area = Math.PI*radius*radius; } public Circle() { this(1.0); }... } Calls the first constructor

©SoftMoore ConsultingSlide 5 Static Fields (a.k.a. Class Variables) In general, each object of a class has its own copy of the fields. A static field acts as a global variable for the class. There is only one copy of a static field shared by all the objects of the class (not part of each allocated object).

©SoftMoore ConsultingSlide 6 Static Methods Analogous to static fields, a static method acts for the class as a whole and not for the individual objects of the class. –no implicit object is passed (no this reference) –can access static fields of the class –can access “normal” (non-static) fields only for objects passed as explicit arguments –still obeys access specifiers (public, etc.) Static methods can be invoked like other methods using a reference to an object and the “dot” notation. They can also be invoked directly using the notation ClassName.methodName()

©SoftMoore ConsultingSlide 7 Example: Static Fields and Methods public class X { // keeps track of number of objects of class X private static int objectCount = 0; public X() { ++objectCount; }... /** * Returns total number of objects of class X. */ public static int getObjectCount() { return objectCount; }

©SoftMoore ConsultingSlide 8 Example: Calling Static Methods // invoked via class X System.out.println(X.getObjectCount()); // invoked via an object X x1 = new X(); System.out.println(x1.getObjectCount()); Prefer the notation ClassName.methodName() when accessing static methods.

©SoftMoore ConsultingSlide 9 Static Initialization Blocks class T { static { System.out.println("Class initialization...");... }... } Class level –designated with static modifier –block executed once when class is loaded –can be used to initialize static fields

©SoftMoore ConsultingSlide 10 Generics Example Before Java 5 and generics List customers = new LinkedList();... Customer c = (Customer) customers.get(0); Using generics List customers = new LinkedList<>();... Customer c = customers.get(0); // no cast necessary

©SoftMoore ConsultingSlide 11 A Simple Generic Class public class Pair { private T first; private S second; public Pair(T first, S second) { this.first = first; this.second = second; } public T getFirst() { return first; } public S getSecond() { return second; } }

©SoftMoore ConsultingSlide 12 Type Variables A generic class or interface is declared with a type variable (often simply E) enclosed in angle brackets. The type variable denotes an element type that can be used within the generic class. A generic class can be instantiated with any class or interface type List accounts = new ArrayList<>(); List comps = new ArrayList<>(); A generic class cannot be instantiated with a primitive type such as int or double (use wrapper classes).

©SoftMoore ConsultingSlide 13 Erasure Intuitively, List behaves like a version of List where E has been uniformly replaced by String. This intuition can be helpful, but it's also misleading. Generics are implemented by the Java compiler as a front-end conversion called erasure. Erasure gets rid of (or erases) all generic type information, resulting in raw type, a list of Object. The checks for correctness and consistency are performed only by the compiler.

©SoftMoore ConsultingSlide 14 Example: Pair Class After Erasure public class Pair { private Object first; private Object second; public Pair(Object first, Object second) { this.first = first; this.second = second; } public Object getFirst() { return first; } public Object getSecond() { return second; } }

©SoftMoore ConsultingSlide 15 The Throwable Hierarchy An exception class is any subclass of Throwable. Throwable ErrorException RuntimeException…Exception…Error

©SoftMoore ConsultingSlide 16 Checked Versus Unchecked Exceptions Any exception that derives from class Error or class RuntimeException is called an unchecked exception. All other exceptions are called checked exceptions.

©SoftMoore ConsultingSlide 17 Declaring Checked Exceptions Two special situations –you call a method that throws a checked exception –you detect an error and explicitly throw a checked exception The enclosing method must either handle the exception locally or it must declare the exception as part of its exception specification list. Note that the above requirement applies only to checked exceptions. Unchecked exceptions may be declared in the exception specification list or handled, but it is not required.

©SoftMoore ConsultingSlide 18 Inheritance Inheritance provides the capability to create new classes from existing classes by defining only the additional facilities required by the new class. The new class is said to be a subclass (a.k.a. derived class) of the existing class. The existing class is said to be the superclass (a.k.a. base class) of the new class. The subclass inherits the fields and methods of its superclass. Classes support the concept of abstract data types (user-defined types). Inheritance extends this support to allow expression of hierarchical type/subtype relationships.

©SoftMoore ConsultingSlide 19 Inheritance in Java Java supports single class inheritance only Example: public class Employee {... } public class Manager extends Employee {... } Methods defined in the superclass can be inherited or overridden. Constructors are not inherited, but the constructor for the superclass can be called by the constructor for the subclass to initialize inherited fields. Employee Manager

©SoftMoore ConsultingSlide 20 The Keyword super The keyword super refers to superclass of this object. Example: Calling a superclass method public class Manager {... String getName() { return "manager " + super.getName(); } Example: Calling a superclass constructor public Manager(int employeeId) { super(employeeId); }

©SoftMoore ConsultingSlide 21 Defining Constructors for Subclasses If the constructor for a subclass does not explicitly call a constructor for the superclass, then the default constructor for the superclass is called implicitly prior to the initializations defined in the subclass constructor. public class Manager extends Employee { public Manager() {... // Employee() called implicitly }... } Note: If the superclass does not have a default constructor, then a superclass constructor must be called explicitly as the first statement.

©SoftMoore ConsultingSlide 22 Object Type Equivalence Inheritance is used to represent the “is-a” relationship between classes (a Manager is an Employee ). In general, you can use an object of a subclass in places calling for an object of its superclass without an explicit cast. Employee m = new Manager(); An Employee is not necessarily a Manager Manager m = new Employee(); // error! Given an Employee, you can try to cast it to a Manager Manager m = (Manager) someEmployee; but if it really isn't, there will be a runtime exception Manager m = (Manager) (new Employee()); // error!

©SoftMoore ConsultingSlide 23 Final Methods and Classes A subclass cannot override a method that has been declared as final. public final String getName() { return name; } A class may be declared final. –may not be extended (i.e., no subclasses) –all methods are automatically final public final class Executive extends Manager {... } Tradeoff: performance versus flexibility

©SoftMoore ConsultingSlide 24 Polymorphism Calls to non-static, non-final methods are bound dynamically at run time to the appropriate method. –The method actually called is determined at runtime based on the object referenced and not the class declared for the variable. The word polymorphism is Greek for “many forms.” In object-oriented programming terminology, polymorphism means that we can use a method name that is shared up and down a class hierarchy, with each class in the hierarchy implementing the action in a way appropriate to itself. In Java, polymorphism is implemented using non-static, non-final methods.