Java III

Inheritance

  • Inheritance is the ability to define classes from other classes, there by inheriting their methods and members
  • Inheritance aims to do two things
    • Provide a mechanism for code reuse
    • Proivde a way to organize a program similarly to the problem space

Base Class

  • The base class should contain all commonalities of the derived classes
    • All shapes have an area
    • All people have a name
  • Base classes can also be used to enforce consitency in method naming and how interaction takes place

Derived Class

  • The derived class inherits all methods and members of the base class, in general.
  • The derived class can do one of three things for each method in the base class:
    • Refine the base class methods
      • Call the base class method and then do something else
    • Replace the base class methods
      • Do something else entirely, hopefully still related
    • Do Nothing
      • Inherit the method as is

Base Class in Java

  • Almost any class can be inherited from in Java
  • To prevent a class from ever being inherited from, define it with the keyword final
  • A base class can still have private methods and members
    • These will not be inherited

Derived Class in Java

  • Each class in Java can have one direct base class
  • The syntax to indicate inheritance in Java is to use the extends keyword in class definition
  • The base class's constructor is always called
    • If it is not explicitly called, then the constructor with no parameters is called
    • To call the base constructor manually use the keyword super
      public class SomeClass extends BaseClass{
            public Someclass(int var1, bool var2,String var3){
                super(var1,var2);
            }
        }
      

Method Overriding

  • A method in the derived class with a same name as one in the base class
  • Should do something similar - but this is up to the programmer
  • Any method that is not overriden will be inherited
  • Can call the base method from the parent using the super keyword
    public class SomeClass extends BaseClass{
        public int aMethod(){
            return super.aMethod() + 10;
        }
    }
    

Multiple Inheritance

  • Once a language designer decides to include inheritance, they face a decision: How much inheritance at for each class
  • Some languages like C++ allow a class to inherit from multiple other classes
    • This can improve modeling of the problem space
      • i.e. A teaching assistant is a teacher and a student
  • Multiple Inheritance causes challenges
    • What to do a method is found in more than one base class?
      • Which do we call?
    • What to do when two or more base classes are themselve derived from a single class (Diamond Inheritance Pattern)
      • How many copies of members are there?

Multiple Inheritance

  • When there are multiple methods with the same name inherited, it is up to the derived class to make them unambigous
    • Explicitly override the method in question, even if its just to call the base class method
      void doSomething(int value){
            base1::doSomething(value);
        }
      
    • If you still want to permit the other methods to be used, rename them
      void doAnotherThing(int value){
            base2::doSomething(value)
        }
      

Multiple Inheritance

  • When two base classes are derived from the same class, there is nothing the programmer of the new derived class can do
  • Proper behavoir depends on how the base classes were implemented
    • In C++, inheriting a class as virtual prevents multiple copies of member variables being made
    • Example from An Introduction to Object Oriented Programming ,Timothy Budd, 1991
class Stream{
                File *fp;
            };

            class InStream : public virtual Stream{
                int open(File *);
            };

            class OutStream : public virtual Stream{
                int open(File *);
            };

            class InOutStream : public InStream, public OutStream;
            {
            };

Abstract Classes

  • It is often useful to only define method names and return types, rather than any implementation
  • In Java we define an asbtract method in the base class, which enforces that it must be overridden
  • In order to have an abstract method, a class must be declared as abstract
  • An abstract class can never be instantiated
public abstract class SomeAbstract{

      public int i = 0;
      public int aMethod(){
          return i;
      }

      public abstract void abstractMethod();
  }

Interfaces

  • Java doesn't allow multiple inheritance, but it does have a compromise solution avaliable, called interfaces
  • An interface in Java has no members, and no method definitions, only declerations.
  • Any class can implement multiple interfaces
  • Because there is no method definitions, it is ok if multiple interfaces require the same method
public interface anInterface{
    public void aRequiredMethod();
    public void anotherOne();
}

public class Implementation implements anInterface{

        public void aRequiredMethod(){...}
        public void anotherOne(){...}
}

Interfaces vs Abstract Classes

  • Interfaces and Abstract classes seem pretty similar, why does Java have both
  • Abstract classes are useful to enforce overidding of particular methods
    • They can still have some methods defined
    • They can still have members
  • Interfaces enforce more constraints that allow them to be used more like multiple inheritance

The Square and the Rectangle

The following summarizes the excellent discussion found in Object-Oriented Design Using Java , Dale Skrien, 2009

  • In Geometry a square is a rectangle
  • We might be tempted to make a class square inherit from rectangle
    • What happens when we want to change the size of the square, but rectangle allows us to change height and width independently
  • When mapping the problem space to classes, it is important to pay attention to the assumptions that are made in the problem space

Negatives of Inheritance?

  • At one time, memory space was an issue, but this is no longer a concern
  • The real cost is in the complexity of the code
    • The more ancestor classes a class inherits from, the further segmented its code base is.
    • This can be good for code-reuse, but can make debugging very difficult
  • Can be overused when it doesn't fit the problem clearly

Polymorphism

  • Polymorphism is often considered the third principal part of OOP along with encapsulation and inheritance
    • It builds upon both these ideas
  • When creating a new object that is a derived type, we can store it in a variable that is the same type as its base class, or a interface it implements
    • ArrayList and LinkedList both implement the List interface
List list = new LinkedList();
List list = new ArrayList();
  • When the following code is executed, the correct method is chosen at runtime.
list.clear();

Additional Sources Used

Object-Oriented Design Using Java, Dale Skrien, 2009
An Introduction to Object-Oriented Programming, Timothy Budd, 1991