Chapter 11
Advance Inheritance Concepts

Student Learning Outcomes

1.
Create and use abstract classes
2. Use dynamic method binding
3. Create arrays of subclass objects
4. Use the Object class and its methods
5. Use inheritance to achieve good software design
6. Create and use interfaces
7. Create and use packages

I
mportant Points:

1. Create and use abstract classes.  A concrete class is one from which you can instantiate objects. A class such as Employee that you create only to extend from is not a concrete class; it is an abstract class.
a. Two methods with abstract classes.  
- Nonabstract methods
, like those you can create in any class, are implemented in the abstract class and are simply inherited by its children.
- Abstract methods have no body and must be implemented in child classes.
b. If you declare a method to be abstract, you must also declare its class to be abstract.
c. If you create an empty method within an abstract class, the method is an abstract method.
d. If you declare a class to be abstract, its methods can be abstract or not.
e. When you create a subclass that inherits an abstract method, you write a method with the same signature.
f. You are required to code a subclass method to override every empty abstract superclass method that is inherited. Either the child class method must itself be abstract, or you must provide a body, or implementation, for the inherited method.
g. Abstract classes usually have one or more empty abstract methods.
h. An abstract method has no body, curly braces, or statements.
 
2. Using Dynamic Method Binding.  Superclass objects are not members of any of their subclasses and because every subclass objects is a superclass member, you can convert subclass objects to superclass objects. If a superclass is abstract you can indirectly create a reference to a superclass abstract object which points to a memory address held in a variable.
a. An applicationís ability to select the correct subclass method is known as dynamic method binding. Also called late method binding.
b. The opposite of dynamic method binding is static (fixed) method binding. Instance methods use dynamic binding, class methods use static method binding.
c. Dynamic binding makes programs flexible, static binding operates more quickly.
d. Polymorphic behavior can apply to nonrelated classes as well. When it depends on method overloading, it is called ad-hoc polymorphism. When it depends on using a superclass as a method parameter, it is called pure polymorphism or inclusion polymorphism.
e. Using a superclass as a method parameter type. Dynamic method binding is most useful when you want to create a method that has one or more parameters that might be one of several types.
f. If a parent is a parent class and child is its child, then you can assign a child object to a parent reference

3. Creating arrays of subclass objects.When you create an array of superclass references, it can hold subclass references which is true whether the superclass in question is abstract or concrete.
a. When you create an array in JAVA, you are not constructing objects. You are creating space for references to objects. Every array of objects is really an array of object references.
b.
int Animal [] animalRef=new Animal[3]; //this reserves memory for three object references
c. You can assign subclass objects to an array that is their superclass type.

4. Using the Object Class and Its Methods
a.
public class Animal{} is the same as public class Animal extends Object{} because the object class is loaded every time you start JAVA.

Method

Description

Object clone()

Creates and returns a copy of this object

boolean equals(object obj)

Indicates whether some object is equal to the parameter object

void finalize()

Called by the garbage collector on an object when there are not more references to the object

Class<?>getClass()

Returns the class to which this object belongs at run time.

int hashCode()

Returns a hash code value for the object

void notify()

Wakes up a single thread that is waiting on this objectís monitor

void notifyAll()

Wakes up all threads that are waiting on this objects monitor

String toString()

Returns a string representation of the object

void wait(long timeout)

Cause the current thread to wait until either another thread invokes the notify() method or notifyAll() method for this object, or a specified amount of time has elapsed.

void wait(long timeout, int nanos)

Causes the current thread to wait until another thread invokes the notify() or notifyAll() method for  this  object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

a. Using the toString() methodConverts an Object into a String that contains information about the object.
b. Hash code - calculated number used to identify an object that is returned by the
toString() method. 

String dogString=myDog.toString();

c.
toString() is good for trouble shooting. It converts relevant data into a string. Since toString() originates in the object class it will compile with any object whose details you want to see:

public class TestBankAccount
{
     public static void main(String[] args)
     BankAccount myAccount= new BankAccount(123, 4567.89);
     system.out.println(myAccount.toString()):

//This will display the data from the object BankAccount the way BackAccount processes the data which is wrong.
}

d. Using the equals() method.  Takes a single argument, which must be the same type as the type of the invoking object.
e. Example of equals()

If(someObject.equals(someotherobjectofthesametype))
       System.out.println("The objects are equal");


f. Other classes, such as the String class, also have their own equals() methods that overload the object class method. Two string objects are considered equal only if their String contents are identical.
g. The object class
equals() returns a Boolean value indicating the objects are equal. Two objects of the same class are equal only if they have the same hash code. That is, one is a reference for the other. If you want to consider objects to be equal based on their contents you must write your own equals() method for your classes. For example:

    public boolean equals(BankAccount secondAcct)
    {
        boolean result;
        if(acctNum==secondAcct.acctnum && balance ==secondAcct.balance)
        result = true;
        else
        result=false;
        return result;
    }


h. When you define a class, if you do not explicitly extend another class, your class is an extension of the object class.
i The
.object class is defined in the java.lang package, which is imported automatically ever time you write a program.

5. Using Inheritance to Achieve Good Software Design. When you create a useful, extendable superclass you gain several advantages.
a. Subclass creators save development time because much of the code needed for the class has already been written
b. Subclass creators save testing time because the super class code has already been tested and probably used in a variety of situations.
c. Programmers who create or use new subclasses already understand how the superclass works, so the time it takes to learn the new class features is reduced.
d. When you create a new subclass in Java, neither the superclass source code nor the superclass bytecode is changed. The superclass maintains it integrity.


6. Creating and Using Interfaces
a. Multiple inheritance is the capability to inherit from more than one class. -Not allowed in JAVA
b. In Java, a class can inherit from a superclass that has inherited from another superclass - single inheritance with multiple generations.
c. Interface is an alternative to multiple inheritance. It looks much like a class except that all of its methods (if any) are implicitly public and abstract and all of its data items (if any) are implicitly public, static, and final. An interface is a description of what a class does, but not how it is done.
d. An interface is a device or a system that unrelated entities use to interact.
e. Example of interface:


public interface Worker    //this interface has a single method named work().
{                           //When any class implements Worker, it must either include a work()method or the
    public void work();    //new class must be declared abstract, and then its descendants must implement the method.
}


f. A class can extend another class without implementing any interfaces. A class can also implement an interface even though it does not extend to the other class. When a class both extends and implements, like the
WorkingDog class, the implements clause follows the extends clause in the class header.

public class WorkingDog extends Dog implements Worker
{
     private int hoursOfTraining;
     public void sethoursOfTraining(int hrs)
     {
         hoursOfTraining=hrs;
     }
     {
         return hoursOfTraining;
     }

     public void work()
     {
         speak():
         System.out.println("I am a dog who works");
         System.out.println(" I have  " + hoursOfTraining + " hours of professional training!");
     }
}

g. An interface specifies only the messages to which an object can respond: an abstract class can include methods that contain the actual behavior
h. You also create an interface when you want a class to implement behavior from more than one parent.
i. Java has many built in interfaces with names such as
Serializable, Runnable, Externalizable.
j. Creating Interfaces to Store Related Constants.  Interfaces can contain data fields, but they must be public and static and final. No private allowed because you cannot create interface objects.

    public interface PizzaConstants
    {
        public static final int SMALL_DIAMETER=12;
        public static final int LARGE_DIAMETER=16:
        public static final double  DOUBLE tax_rate=0.07;
        public static final String COMPANY = "Antonio's Pizzeria";

    } 

The purpose in creating an interface containing constants is to provide a set of data that a number of classes can use without having to redeclare the values.

   public class PizzaDemo implements PizzaConstants  //This line make available the constants defined in PizzaConstants.

k. All of the methods in an interface are implicitly public and abstract, and all if its data items (if any) are implicitly public, static, and final.
l. When a class inherits from another, the child class can use the nonprivate, nonoverridden members of its parents class, but when a class uses an interface, it must implement its own version of each method.

7. Creating and Using Packages.  A package is a named collection of classes:  When you create classes you place related classes in a package. The package can be used by other programmers.
a. If you do not use one of the three access specifiers
public, private, or protected for a class then it has default access which means that the unmodified class is accessible to any other class in the same package.
b.
.class files are the files you place in a package so other programmers can import them.
c. If you do not specify a package for a class, it is placed in an unnamed default package. If a class in not public, it can be used only by other classes within the same package.
d. a package declaration must be the first statement in the file. Import statements follow the package declaration. The package statement must appear outside the class definition.
e.
package com.course.animals;    This statement says that the compiled files will be placed in the animal folder contained in the course folder contained in the com folder.
f.
javac -d . Animal.java   This is a compiler option for the javac command   -d (for directory indicate you want to place the generated .class file in a folder.
The dot (period) indicates that the path shown in the package statement in the file should be created within the current directory.
g. Every package must have a unique name.  SunMicro Systemís naming convention gives the internet domain name in reverse for a package. 
earl.wylie.solano.edu with a package called grades would be written edu.solano.wylie.earl.grades.
h. In the animal class the statement
package com.course.animals; places the animal.class in C:\com\course\animals. To import the animal class import com.course.animals.Dog; or Cat;
i. Class naming conflicts are sometimes called collisions.
j. Typically you place
.class files in a package so other programmers can import them into their programs.
k. Java creators have defined a package-naming convention in which you use your internet domain name in reverse order.