Interfaces and Inner Classes

  • Java does not support multiple inheritance
  • A subclass can only have one direct parent
  • Modes of transportation can be refueled
  • Some modes of transportation can fly
  • Some modes of transportation must drive on specified roads

Interfaces, Motivation

  • Multiple inheritance subsitute, pull from one class
  • Classes that implement that interface

Nested Classes

  • Can specify a full class definition inside another class
  • The inner class can access all of its own members, as well as all of the members of the class it is in
  • Often used for helper classes
    • Classes whose only purpose is really to help with the outer class
    • Keep classes directly related to the outer class rgih with the outer class, instead of being in different files

Generics Motivation

  • Generics are a lot like templates in C++
  • Goal of generics
    • Allows a class to be written once and suppor the use of many data types

Basic Syntax for Generic Class

public class MyGenericClass <DataType>

public DataType myGenericDataMember;
// or
public DataType myMethod(double x, DataType y);

Using extends to Restrict Data Types

  • Uses compareTo method -compareTo is in the Comparable interface, which thte Integer class implements
  • When making the class generic, we're saying we support other data types too
  • Need to be able to say this class is generic, but will only work on types that implement the Comparable interface
  • This is done using keyword extends
  • There is no differentiation between whether class must extend another class or implement an interface - extends is used for both

results matching ""

    No results matching ""