> inheritance in java ~ Online tutorial

inheritance in java

Inheritance
  • Inheritance is a mechanism for enhancing existing classes.
  • If you need to implement a new class and a class representing a more general concept is already available, then the new class can inherit from the existing <a href="http://573120-9-kcfw4skv8zbsfteak.hop.clickbank.net/" target="_top">class</a>.
For example, suppose you need to define a class SavingsAccount to model an account that pays a fixed interest rate on deposits. You already have a class BankAccount, and a savings account is a special case of a bank account. In this case, it makes sense to use the language construct of inheritance.
Inheritance is a mechanism for extending existing classes by adding methods and fields.
Syntax:
class SavingsAccount extends BankAccount
{
new methods
new instance fields
}
1)In the SavingsAccount class definition you specify only new methods and
instance fields.
2)The SavingsAccount class automatically inherits all methods and
instance fields of the BankAccount class.
For example, the deposit method automatically applies to savings accounts:

SavingsAccount collegeFund = new SavingsAccount(10);
// Savings account with 10% interest
collegeFund.deposit(500);
// OK to use BankAccount method with SavingsAccount object




Program

class SubclassName extends SuperclassName

{

methods

instance fields

}

Example:

public class SavingsAccount extends BankAccount

{

public SavingsAccount(double rate)

{

interestRate = rate;

}

public void addInterest()

{

double interest = getBalance() *

interestRate / 100;

deposit(interest);

}

private double interestRate;

}

Purpose:

To define a new class that inherits from an existing class, and define the methods

and instance fields that are added in the new class

Buy It now




Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: BloggerYard.Com

0 comments: