Abstract and Nested Classes

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

Lecture 5: Interfaces.
OOP with Java, David J. Barnes Interfaces1 A set of features offered by a class. Often offered by more than one class. –Iterator : Returned by the iterator.
Written by: Dr. JJ Shepherd
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Tirgul 1 Today’s subjects: –First programming exercise. –Java reminder & completions : reference data types, cloning, inner classes, packages. –Short reminder.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Lecture 9 Concepts of Programming Languages
Chapter 10 Classes Continued
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Based on OOP with Java, by D.J. Barnes 1 Review 4 View classes as modules Encapsulate operations 4 View classes as struct types Encapsulate data 4 View.
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
OOP Languages: Java vs C++
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CS-434: Object-Oriented Programming Using Java Week 2
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Lecture 10 Documentation, Garbage Collection, and Nested Classes/Interfaces.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Advanced Programming Rabie A. Ramadan vpro/ Lecture 4.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
OOP with Java, David J. Barnes/Eric Jul Defining Classes1 Object State and Complexity Objects maintain a state. State is represented by a set of attributes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Nested Classes CompSci 230 S Software Construction.
Session 18 Lab 9 Re-cap, Chapter 12: Polymorphism & Using Sound in Java Applications.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
A cannon game ?. Simple version angle from command line, one shot only Coordinate system is “upside-down”: Use dy(int) method to transform y coordinate:
Creating a GUI Class An example of class design using inheritance and interfaces.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Classes Revisited Chapter 8.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Advanced Programming Practice Questions Advanced Programming. All slides copyright: Chetan Arora.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
SCJP 5, 1/7 Declarations, Initialization and Scoping
Chapter 7: Cloning and RTTI
CompSci 230 S Software Construction
Lecture 9 Concepts of Programming Languages
Lecture 4: Interface Design
null, true, and false are also reserved.
Java Programming Language
Conditional Statements
Chapter 8 Class Inheritance and Interfaces
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Abstract and Nested Classes Abstract classes: Incomplete abstract classes. Complete abstract classes. Comparison with interfaces. Nested Classes: Static nested classes. Inner classes. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Abstract Classes Class has abstract prefix. Instances may not be constructed. Incomplete methods: just a header. Method has abstract prefix. Implicit in interface definitions. Objects have no meaningful existence. Class elements used by defining sub classes. OOP with Java, David J. Barnes Abstract and Nested Classes

The Abstract Number Class public abstract class Number implements Serializable { public abstract int intValue(); public abstract long longValue(); public abstract double doubleValue(); public abstract float floatValue(); public byte byteValue(){ ... } public short shortValue(){ OOP with Java, David J. Barnes Abstract and Nested Classes

Incomplete Abstract Classes Define a common interface for multiple sub classes. Sub class implementations vary. Implementation of floatValue, in Number sub classes, depends on type of attribute. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes The Double Sub Class public class Double extends Number { public Double(double value){ this.value = value; } ... // This probably involves loss of information. public float floatValue(){ return (float) doubleValue(); // The value being wrapped. private final double value; OOP with Java, David J. Barnes Abstract and Nested Classes

Complete Abstract Classes No abstract methods. Independent instantiations have no meaning. ChessPiece super class of Rook, Knight, etc. Sub classes provide additional or overriding functionality. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract Class or Interface? Interface methods are abstract. Interfaces do not have constructors. Abstract classes avoid the need to define duplicate method bodies. Multiple inheritance. Extending an abstract class prevents extension of a second class. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Object Cloning All classes inherit a clone method. Returns an identical copy. A shallow copy, by default. A deep copy is often preferable. The (empty) Cloneable interface must be implemented. CloneNotSupportedException OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes A Cloneable Point class Point implements Cloneable { ... public Object clone() { try{ // A shallow copy. return super.clone(); } catch(CloneNotSupportedException e){ // This should never happen! throw new Error("Cloning error: "+e); OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Preventing Cloning Prevention might be necessary. A unique attribute - database lock or open file reference. Not sufficient to omit Cloneable. Sub classes might implement it. clone should throw an exception: CloneNotSupportedException. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes An Unclonable Class class NotCloneable { ... // Explicitly prevent sub class cloning. public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("..."); } OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Static Nested Classes (aka Nested Top-Level Classes!?). Used to show strong coupling between two classes. VariableController and HeaterLevelException. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes class VariableController extends HeaterController { // Class constants for basic temperatures. public static final int DefaultLevel = 16, MinLevel = 5, MaxLevel = 30; // An illegal temperature level has been set. public static class HeaterLevelException extends RuntimeException { public HeaterLevelException(String message){ super(message); } // The attached heater's current level. public int getLevel(){ ... OOP with Java, David J. Barnes Abstract and Nested Classes

Static Nested Class Names Nested class has a qualified name. VariableController.HeaterLevelException Separate .class file created. VariableController$HeaterLevelException.class Qualified name used outside the enclosing class. catch(VariableController.HeaterLevelException e) OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Inner Classes Non-static nested classes. Instances only exist within the context of an enclosing object. May not have static members. May access private members of the enclosing class. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Inner Class Roles Used to fulfill distinct roles in support of an enclosing object. Subordinate inner class. Interpretational inner class. Local inner class. Anonymous inner class. Very common in supporting GUIs. OOP with Java, David J. Barnes Abstract and Nested Classes

Subordinate Inner Classes Used to break up a single large class. Implement subordinate sub-tasks. E.g., logging a ship's movements. Keeps enclosing class less cluttered. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes public class LoggingShip extends SimpleShip { ... public void move(){ super.move(); getLogger().log(); } protected class ShipLog { protected void log(){ Position p = new Position(getX(),getY()); getLog().add(p); protected LinkedList getLog(){ return positionLog; private LinkedList positionLog = new LinkedList(); private final ShipLog logger = new ShipLog(); OOP with Java, David J. Barnes Abstract and Nested Classes

Interpretational Inner Classes Interpreting an object’s data to outside objects. Independently of the internal representation. E.g. Iterator and Enumeration implementations. DataValues - a collection of numbers. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes public class DataValues { public void add(double d){ getNumbers().add(new Double(d)); } public double get(int index) throws IndexOutOfBoundsException { Double d = (Double) getNumbers().get(index); return d.doubleValue(); public int numItems(){ return getNumbers().size(); ... protected LinkedList getNumbers(){ return numbers; private final LinkedList numbers = new LinkedList(); OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes public class DataValues { public Iterator getPositives(){ return new PositiveSelector(); } protected class PositiveSelector implements Iterator { public boolean hasNext(){ return nextPosition() >= 0; public Object next() throws NoSuchElementException { int i = nextPosition(); if(i >= 0){ Object o = getNumbers().get(i); setIndex(i+1); return o; else{ throw new NoSuchElementException(); ... OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Local Inner Classes A class defined within a method. Permitted within any block. Instances may only be created from within that method. No visibility modifier is used. Instances may access the method’s final variables and arguments. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes public class DataValues { public Iterator selectAbove(final double limit){ class AboveSelector implements Iterator { ... protected int nextPosition(){ int i = getIndex(); final int howMany = numItems(); while(i < howMany){ if(get(i) > limit){ return i; } i++; return -1; return new AboveSelector(); OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Anonymous Classes Local classes often do not require a name. When they implement an interface or extend a super class. When definition and creation are closely linked. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes public class DataValues { ... public Iterator selectAbove(final double limit){ return new Iterator() { public boolean hasNext(){ } public Object next(){ }; OOP with Java, David J. Barnes Abstract and Nested Classes

Anonymous Classes in GUIs. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Picture extends JFrame { Container contents = getContentPane(); // Add a button to quit the application. JButton quit = new JButton("Quit"); quit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); contents.add(quit,"South"); ... OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Inner Classes and this class Outer { // 'this' accessible from here. ... class Middle { // 'this' and 'Outer.this' accessible from here. class Innermost { // 'this', 'Middle.this' and 'Outer.this' // accessible from here. } private Innermost i = new Innermost(); private Middle m = new Middle(); OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Review Abstract classes are incomplete and must be sub classed to be useful. Abstract classes offer an alternative to interfaces where partial implementation is useful. Classes implement cloning by implementing the Cloneable interface. OOP with Java, David J. Barnes Abstract and Nested Classes

Abstract and Nested Classes Review (cont.) Nested classes may be static nested classes or inner classes. Inner class instances always exist within the context of an enclosing object. Inner classes have access to the private members of their enclosing class. Inner classes are useful for fulfilling a range of roles within their enclosing class. OOP with Java, David J. Barnes Abstract and Nested Classes