Java – Inheritance, Interfaces Kurt Schmidt Intro Java Classes Inheritance Casting Containers Interfaces Exceptions Nested Classes Java – Inheritance, Interfaces Kurt Schmidt Dept. of Computer Science, Drexel University November 13, 2017 These notes are intended for students familiar with C++ Originally from Bruce Char & Vera Zaychik
30
Embed
Java Inheritance, Interfaces - College of Computing …Java – Inheritance, Interfaces Kurt Schmidt Intro Java Classes Inheritance Casting Containers Interfaces Exceptions Nested
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Java – Inheritance, Interfaces
Kurt Schmidt
Dept. of Computer Science, Drexel University
November 13, 2017
These notes are intended for students familiar with C++Originally from Bruce Char & Vera Zaychik
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Intro
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Java is Object-Oriented
Inheritance in Java is rather like inheritance in C++. Somedifferences to note:
No multiple inheritanceWe use Java Interfaces
All methods are virtualAll variables of type Object are references, so...
There is no destructorfinalize() is called when object is released back tothe heapSo, not reliably called
Java allows static attributes of any type to be initialisedat the declarationJava allows classes to be defined inside a classJava allows unnamed classes
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Java Classes
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Classes as Namespaces
The Math class, e.g., is simply a container for methods andconstants.
Can’t be instantiatedThe default constructor is made private
The class is final – can’t be subclassedAll methods are public static
Math.sin( a ) ;Math.exp( x ) ;
Constants are public static attributes
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Inheritance
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Inheritance vs. Aggregation
Inheritance is the is-a relationshipA square is a shapeAn employee is a personA professor is an employeeSo, a professor is a personIt’s not perfect
Aggregation is the has-a relationshipA square has a colorAn employee has an addressA car has an engine
And 4 tires
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Inheritance
Given a simple class:
public class Person {protected String _name ;public Person( String n ) { _name = n ; }public String getName() { return _name ; }
}
We can define a subclass:
public class Professor extends Person {protected String _id ;public Professor( String n, string i ){ super(n) ; _id = i ; }public String getName(){ return "Prof. " + _name ; }
}
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Abstract Superclass
An abstract class can not be instantiatedIt typically contains method declarations, w/outdefinitions
These are behaviors that subclasses must provide to bemeaningfull objectsUse the @Override annotation
E.g., a closed shape might well know its color, anddeclare a method to compute its area
All closed shapes have an areaComputed differenty for each shapeArea of an abstract shape is meaningless
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Abstract Superclass – example
public abstract class ClosedShape {protected Color _fill ;public ClosedShape( Color c ) { _fill = c ; }public Color color() { return _fill ; }public abstract double getArea() ;
}
We create an actual shape
public class Circle extends ClosedShape {protected double _radius ;
public Circle( Color c, double r ){ super(c) ; _radius = r ; }
Objects can be cast up the treeAlways safeExplicit cast not neededOnly methods from ancestor may be calledRemember, all methods are virtual
ClosedShape s = new Circle( Color.BLUE, 3 ) ;
Objects can be cast down the treeMight throw ClassCastExceptionRemember, all methods are virtual
Circle c = (Circle) s ; // This works fineSquare q = (Square) s ; // This throws exception
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
instanceof Operator
We can test objectsAn object of a subclass is always an instance of anancestorAn object of a class is not, generally, an instance of adescendant
ClosedShape c = new Circle( Color.PURPLE, 8 ) ;...if( c instanceof Square ) System.out.prinln( "c is a Square" ) ;if( c instanceof Circle ) System.out.prinln( "c is a Circle" ) ;if( c instanceof ClosedShape )
System.out.prinln( "c is a ClosedShape" ) ;
c is a Circlec is a ClosedShape
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Containers of Shapes
We can create containers of shapes:
public static void main( String [] args ){
GridLoc l = new GridLoc( 1, 2 ) ;ArrayList<Shape> zoo = new ArrayList<Shape>() ;zoo.add( new Circle( 3, l )) ;zoo.add( new Square( 5, l )) ;
Java does not support mulitple inheritanceThis is not a bad thingMultiple inheritance is messy, both in design andimplementation
An interface describes behaviors which must besupplied by any implementing class
It declares methodsIt does not define anyAttributes, however, can be defined
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Interfaces
An interface can “inherit” from one or more otherinterfaces:
public interface Stealthy{
public void stalk() ;}
public interface Predator extends Stealthy{
public void pounce() ;}
A class might implement multiple interfaces:
public class Cat extends Animal implements Predator, Yowler{ ... }
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Containers and Interfaces
Instances of an class implementing an interface can beviewed as objects of that type
A KeyListener object, whatever else it is, has methodskeyTyped, keyPressed, and keyReleasedAll Animals that implement the Yowler interface can becontained together:
public static void main( String [] args ){
ArrayList<Yowler> zoo = new ArrayList<Yowler>() ;zoo.add( new Cat( "Sylvester" )) ;zoo.add( new Wolf( "Nighteyes" )) ;...for( Yowler y : zoo ){
y.singAncientSongOfYourPeople() ;}
}
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Exceptions
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
Library Exceptions
These are the exceptionsin the Java standard libraryExceptions in darker boxesare checked exceptions
Must be caught, or listedin a throws statementAll should be so listed
Inherit off of any of these tomake your own exceptions
No behavior need bedefinedIts value is its type
Taken from Cay Horstmann’s Big Java, 4th ed.
Java –Inheritance,Interfaces
Kurt Schmidt
Intro
Java Classes
InheritanceCasting
Containers
Interfaces
Exceptions
NestedClasses
User-Defined Exceptions
public class ThatsOdd extends IllegalArgumentException{
public ThatsOdd( String s ) { super( s ); }}
Can be used as any other exception:public static void foo( int i ) throws ThatsOdd {
if( i%2==1 )throw new ThatsOdd( "We’re partial to evens, in this method." ) ;