You are on page 1of 5

Inheritance In the real world, objects arent usually one-of-a-kind. Most objects have similarities to other objects.

Cars, for example, are similar to trucks. Both cars and trucks are examples of vehicles-objects that can move and carry other objects. In Java, relationships such as the one between cars and vehicles are

expressed using a feature known as inheritance. The idea of inheritance is a natural one. As humans, we inherit from our parents. Like it or not, many of our properties are genetically influenced, from our hair color to our height. Inheritance is one of the basics tenets of object-oriented programming a class is allowed to have a parent from which it inherits some of its state and behavior. Lets return to our car example. Cars have much in common, so there would be no point for a car designer to start from scratch when designing a new car. It can be taken for granted that a car has certain components wheels, a steering wheel, and engine, and so forth. We can also assume certain behavior: turn on engine, accelerate, press brake, and the like. So a car designer can focus on what distinguishes the new model from automobiles in general. In programming using objects, well use inheritance for a similar reason. When we need a new class, well try to create it from and existing class. That way, we wont be starting from scratch every time. Instead, well be able to inherit the variables and methods we need to make the new class unique. In Java, inheritance is accomplished by extending an existing class. To indicate that one class extends another, all we need to do is put the work extends in the class declare preceded by the name of the new class and followed by the name of the class thats being extended. public class Car extends Vehicle{ . } Car is said to be a subclass of Vehicle, and Vehicle is said to be the superclass of Car. A subclass inherits the variables and methods of its superclass, with the exception of constructors, private variables, and private methods. Inherited variables and methods behave as though they were declared in the superclass.

Writing a Subclass An example, lets develop a SavingsAccount class from the Account class (in object notes). A savings account has all the properties of an ordinary bank account: it has a balance it can be opened or closed; money can be deposited or withdrawn, and so on. In addition, a savings account has an interest rate associated with it. At periodic intervals, money is added to the account based on the interest rate and the account balance. Lets assume that different savings account can have different interest rates, which means that each SavingsAccount object will need to store an interest rate. Well need access methods to get and set the interest rate.

public class SavingsAccount extends Account{ private double interestRate;

public double getInterestRate() { return interestRate; } public void setInterestRate(double rate){ interestRate=rate; } An instance of a subclass stores al the instance variables of the superclass, plus all the instance variables defined in the subclass. Even the superclasss private variable, which arent inherited, are still stored in instances of the subclass. For example, a SavingsAccount object will contain two variables a SavingsAccount object

SavingsAccount object

balance---500 intersetRate 4.25

If savingAcct is a SavingsAccount variable, the following statements are all legal: System.out.pirnt (Rate : + savingsAcct.getInterestRate()); savingsAcct.setInterestRate(4.25);

savingsAcct.deposit(500.00); savingsAcct.withdraw(100.00); System.out.pirntln(Balance: + savingsAcct.getBalance());

Writing Subclass Constructors A subclass doesnt inherit constructors from its superclass, so well need to write new constructors for the subclass. Writing a constructor for a subclass is much like writing a constructor for any class. The only problem is initializing the variables that belong to the superclass. These variables are likely to be private so we cant initialize them directly. The constructor for the SavingsAccount class will need to initialize both the balance and interestRate variables. Invoking a superclass constructor, you need to use the word super as though it were the name of the superclass constructor. public SavingsAccount(double initialBalance, double initialRate) { super(initialBalance); // invoke Account constructor interestRate=initialRate; } Illustrating Inheritance Account

SavingsAccount

Account

SavingsAccount

ChequingAccount

Access Modifiers

Access Modifier private protected public None

Meaning Can be accessed only in the same class Can be accessed in the same class or in a subclass Can be accessed in any class Can be accessed in any class in the same package.(as well as protected variables and methods of all classes in the same package.

The protected keyword gives us another way to solve the problem of writing the constructor for the SavingsAccount class. Suppose that we change the declaration of Account class by declaring balance to be protected rather than private. public class Account{ protected double balance; } The SavingsAccount constructors as well as the methods in the SavingsAccount class-will now have direct access to the balance variable, so we can write the SavingsAccount constructor as this: public SavingsAccount(double initialBalance, double initialRate) { balance =initialBalance; interestRate=initialRate; } It is better to declare instance variables to be private rather than protected. If a subclass needs access to these variables, it should be able to call a getter or setter method. If theres no need to expose the getter or setter to all classes, it should be declared protected.

Overriding A subclass can change replace some of its inherited behavior by overriding. If we are unhappy with the behavior of an instance method thats been inherited by a subclass, we can simply have the subclass override the method by supplying one of its own. The new method must have 1. The same name and return type 2. Same number of parameters and the types of corresponding parameters must be the same.

e.g. Lets say our SavingsAccount class has a different needs to print additional information and Account class only prints balance, we can override the printStatement of the Account class to cater allow for the additional interestRate to be included. public void printStatement () { System.out.print (Account balance: + balance); } In our SavingsAccount we can override the printStatement since this print statement only prints part of what we want, we can use it and add to it. public void printStatement() { super.printStatement(); // Print regular statement System.out.print (Interest Rate: + interestRate); // Then print interest rate }

You might also like