inheritance review
Download
Skip this Video
Download Presentation
Inheritance Review

Loading in 2 Seconds...

play fullscreen
1 / 11

Inheritance Review - PowerPoint PPT Presentation


  • 48 Views
  • Uploaded on

Inheritance Review.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Inheritance Review' - garret


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
inheritance review
InheritanceReview
  • Inheritance is used in Java when the objects manipulated form a natural hierarchy using an “is-a” relationship. For Example, suppose we want to design a program for a bookstore that sells several different kinds of books, including children’s books and textbooks. A children’s book is book, and so is a textbook. Therefore, we could define classes ChildrensBookand TextBook as subclasses of the Book class (Book is said to be the superclassof both subclasses).
    • public class Book {

// super class methods & instance fields

}

    • public class ChildrensBookextends Book{

// new methods, overridden methods & instance fields

}

    • public class TextBookextends Book{

// new methods, overridden methods & instance fields

}

  • Subclasses inherit all of the fields and methods of their superclasses (except the constructors). For example, since every Book has a title, a regularPrice, a salesPrice, and the numSold, there is no need to include those fields in the ChildrensBook or TextBook definitions; they will be inherited automatically. Similarly, there is no need to redefine the sell( ), doDiscount( ), mostPopular( ), and newPrice( ) methods; every ChildrensBook and TextBook will automatically have those methods by inheritance.
  • Note that the relationship between a Book and a title is a “has-a” relationship, not an “is-a” relationship. That is why title is a field, not a subclass, of a Book.
slide2
Usually, a subclass will define some new fields and/or methods that are not defined by its superclass. For example, a ChildrensBook might include the age for which the book is intended, and a TextBook might include the name of the course for which it is required:

public class ChildrensBook extends Book{

private intchildsAge;

:

public intgetAge( ) { return childsAge; }

}

public class TextBook extends Book{

private String requiredClass;

:

public String getRequiredClass( ) { return requiredClass; }

}

CONSTRUCTORS:

  • Constructors of a superclass are not inherited by its subclass. However, a subclass’s constructor always call a superclass constructor, either explicitly or implicitly. A superclass constructor is called explicitly using super( ) . For example, we could define a constructor for the ChildrensBook class to include an explicit call to the Book constructor like:

public ChildrensBook(String theTitle, double price, int age) {

super(theTitle, price);

childsAge = age;

When the ChildrensBook constructor is called, it first calls the Book constructor to initialize the title and regularPrice fields; it then assigns the childsAge field itself.

slide3
Note - the explicit call to the superclass’s constructor MUST be the first statement!
  • If a subclass’s constructor does not include an explicit call to one of its superclass’s constructors, then there will be an implicit call to the superclass’sdefault constructor (ie, the compiler will add a call). If the superclass does not have a default constructor, then a compile-time error will be generated!

COMPATIBLE TYPES:

  • Another advantage of using inheritance is that you can use a subclass object anywhere that a superclass object is expected (ArrayLists). For example, because every TextBookis-a Book, any method that has a parameter of type Book can be called with an argument of type TextBook; you do not have to write two versions of the method, one for Book parameters and the other for TextBook parameters. For example, the following method computes the difference between a book’s regular price and its sale price:

public double priceDifference( Book b) {

return( b.getPrice( ) – b.getSalePrice( ) ) ; }

The method will work just fine if it is called with either a Book or a TextBook:

Book book = …

TextBooktb = …

double d1 = priceDifference(book); // Book argument

double d2 = priceDifference(tb); // TextBook argument

Similarly, it is fine to assign from a TextBook to a Book, because a Book is expected on the right-hand side of the = , and TextBookis-a Book:

TextBooktb = …

Book b = tb;

slide4

Although a subclass object can be used anywhere a superclass object is expected, the reverse is not true: in general, you cannot use a superclass object where a subclass object is expected. For example, you cannot call a method that has a TextBook parameter with a Book argument, and you cannot assign from a Book to a TextBook. Assume the following:

public static booleansameClass( TextBook tb1, TextBook tb2 ) {

return ( (tb1. r getRequiredClass( )).equals(tb2. getRequiredClass( )) ); }

The following code would cause two compile-time errors:

Book b = …

TextBooktb = b; // error 1

if(TextBook.sameClass( b, tb) ) // error 2 – assigning b -> tb1!

If you know a particular Book is actually pointing to a TextBook object, then you could use a type cast telling the compiler it’s OK to use that variable where a TextBook is expected!

Book b = new TextBook( …); // b points to a TextBookobj

TextBooktb = (TextBook) b; // No error

if(TextBook.sameClass( (TextBook) b, tb) ) // No error

The following would create a run-time error:

Book b = new Book( …); // b points to a Book obj

TextBooktb = (TextBook) b; // Book is not a TextBook!

if(TextBook.sameClass( (TextBook) b, tb) ) // Error

arraylists
ARRAYLISTS

Class casts are often required when using the standard Java classes that implement collections of objects. For example, the ArrayList class can be used to represent a list of any kind of object; therefore, the return type of its get( ) method is a general superclassObject. This Object will need to be type cast to some subclass object. Consider the following example.

Book b1 = new Book( “Glory Days”, 21.95 );

Book b2 = new Book( “Math for Fun”, 14.99 );

Book b3 = new Book( “Java Jive”, 32.50 );

ArrayList list = new ArrayList( );

list.add(b1);

list.add(b2);

list.add(b3);

for ( inti = 0 ; i < list.size( ) ; i++)

{

Book aBook = (Book) (list.get(i) )

system.out.println(aBook.getPrice( )

}

overloading and overriding methods
OVERLOADING AND OVERRIDING METHODS:

Just as a class can define overloaded methods (same name but different signatures), a subclass can overload methods of its superclassin the same manner. For example, the designer of the ChildrensBook class might want a second version of the mostPopular( ) method that finds the most popular book for children of a particular age:

public static Book mostPopular( Book [ ] bookList, int age)

// precondition: bookList.length > 0

// postcondition: returns the book intended for children of the given age

// that has sold the most copies.

In addition to overloading methods defined by its superclass, a subclass can also override a superclass method; that is, it can define a new version of the method specialized to work on subclass objects. A superclass method is overridden when the subclass defines a method with exactly the same name, the same number of parameters, and the same corresponding parameter types as the superclass.

For example, a special formula might be used to compute the sale price of children’s books (different from the formula used for other kinds of books). In this case, the ChildrensBook class might override the Book class definition of the do Discount( ) method as follows:

public void doDiscount( ) {

salePrice = salePrice * KID_DISCOUNT;

}

slide7

As discussed above, a variable of type Book may actually point to a Book object, a TextBook object, or a ChildrensBook object. The type of the object actually pointed to (not the declared type of the variable) is what determines which version of an overridden method is called. Consider the following example:

Book b = new Book (…);

Book tb = new TextBook(…);

Book cb = new ChildrensBook(…);

b.doDiscount( ); // b points to a Book object,

// so Books doDiscount( ) is called.

tb.doDiscount( ); // tb points to a TextBook object,

// doDiscount( ) was not overridden in TextBook,

// so Books doDiscount( ) is called.

cb.doDiscount( ); // cb points to a ChildrensBook object,

// so ChildrensBookdoDiscount( ) is invoked.

POLYMORPHISM:

Polymorphism denotes the principle that behavior can vary depending on the actual type of an object. It’s a mechanism assuring the correct method is called for an object disguised as a more generic type (multiple meanings)!

slide8

ABSTRACT CLASSES:

Classes closer to the top of the hierarchy are more abstract – the properties and methods of their objects are more general. As you proceed down the hierarchy, the classes become more specific and the properties of their objects are more concretely spelled out. Java allows you to define a class that is officially designated abstract. For example:

public abstract class Solid { …}

An abstract class can have constructors and methods; however, some of its methods may be declared abstract and left without code. For example:

public abstract class Solid {

public abstract double getVolume( );

}

This indicates that every Solid object has a method that returns its volume; but the actual code will depend on the specific type of solid. For example, The Sphere and Cube subclass of Solid will define getVolume( ) differently:

public class Sphere extends Solid {

public double getVolume( ) { return 4/3*Math.PI*Math.pow(radius,3); }

…}

public class Cube extends Solid {

public double getVolume( ) { return Math.pow(side,3); }

…}

slide9

You CANNOT instantiate an abstract class, but you CAN declare variables of its type. Consider the following:

Solid s1 = new Sphere( radius ); //valid - assuming Sphere extends Solid

Solid s2 = new Cube( side ); //valid - assuming Cube extends Solid

Solid[ ] solids = { new Sphere(100), new Cube(100)}; //valid

Solid s = new Solid( ); //invalid – cannot instantiate an abstract class!

Solid s; //valid – s is a pointer to a Shape!

Declaring a superclass method abstract forces the subclass to redefine that method. This is recommended when there exists no good default option for the superclass implementation.

An abstract method has no implementation. This forces the implementation to take place in the subclass.

A class that defines an abstract method, or inherits an abstract method without overriding it, must be declared abstract.

An abstract class cannot be instantiated.

You can also declare classes with no abstract methods as abstract. Thus, preventing others from creating instances of that class, but allowing them the ability to create their own subclasses.

While abstract classes force the programmer to create subclasses in order to implement abstract methods, you have the ability to limit the amount of inheritance.

Using the final keyword prevents other programmers from creating subclasses or from overriding certain methods.

interfaces
INTERFACES:
  • Some objects have more than one “is-a” relationship. For example, consider the following declarations representing some of the individual relationships associated with a university.

public class Person { … }

public class Professor extends Person { … }

public class Student extends Person { … }

public class TeachersAssistant extends Student { … }

    • While TeachersAssistant (TA) is definitely a Student, in some ways, a TA is also a Professor (instructor). Java doesn’t allow you to have TA extend both the Student and Professor classes. You cannot have multiple inheritance!
  • One solution to this problem is to use an interface to define what TeachersAssistant and Professors have in common.

public interface Employee {

void raiseSalary( double amt );

double getSalary( );

}

  • Both TeachersAssistant and Professor can implement , realize, Employee allowing them to redefine those methods which they both have in common.
  • An interface is similar to a class, but it can only contain:
    • public, static, final fields (i.e. constants)
    • public, abstract methods (i.e. headings only, no code at all)
slide11

Given the previous example:

public interface Employee {

void raiseSalary( double amt );

double getSalary( );

}

Note that both methods are implicitly public and abstract – keywords not necessary!

A class can implement one or more interfaces ( in addition to extending one class). It must provide bodies for all the methods declared in the interface, or else it must be abstract.

public class TeachersAssistant implements Employee extends Student {

public void raiseSalary( double amt) {

// Actual Code Here!

}

public double getSalary( ) {

// Actual Code Here!

}

// Likewise Professor would implement Employee but extend Person

// Professor would also define raiseSalary( ) and getSalary( ) accordingly.

Many classes can implement the same interface (e.g. both the TeachersAssistant and Professor classes implement the Employee interface. Interfaces provide a group similar objects.

Employee becomes kind of a place holder for any valid type which realizes it. In other words, Employee is either a TeachersAssistant or Professor!

ad