Aqua Phoenix
     >>  Lectures >>  Java 2  
 

Navigator
   
 
       
   

2.6 Inheritance

UNDER CONSTRUCTION: THIS SECTION IS NOT YET COMPLETE

How do we reuse classes?

Often a class will use another class to represent one of its parts

For example: class Car has an Engine, Chassis and Wheels

Inheritance: Term for a method by which classes are created out of other classes

Cornerstone of OO programming

Idea: write classes that can be reused and extended

Example:

Undergraduate is a type of Student and so is Graduate student

Reuse code:

  • make Undergraduate/Graduate inherit from Student
  • avoid duplicate code

2.6.1 Keyword extends

Extends the definition of existing class

How to declare a new extending class:

class Undergraduate extends Student
That means that Undergraduate will automatically have all the fields and the methods of Student

Undergraduate (subclass) inherits from Student (superclass)

2.6.2 Keyword super

To access the fields or methods of the superclass

super.x (x field of the superclass)

Also can use super() just like this(), but only in constructor (1st statement only)

Note: super.super.x is not allowed!!!

2.6.3 Keyword final

final class: cannot be extended

final field: basically const, cannot be changed

final method: cannot be overridden in subclass