Uploaded by Nicolas alves

Inheritance in JAVA notes (2013 ver)

advertisement
Inheritance in JAVA
What is inheritance?
Inheritance is the capability of a class to use the properties and methods of
another class while adding its own functionality.
So what does this mean for me?
The reason to have a child class is to keep information separate. The child can
inherit all the methods and fields from its parent, but can then do its own
thing.
To best explain the benefits of this, we are going to look at a practical example:
An example of where this could be useful is with an employee records system.
You could create a generic employee class with states and actions that are
common to all employees.
Then more specific classes could be defined for salaried, commissioned and
hourly employees.
The generic class is known as the parent (or superclass / base class) and the
specific classes as children (or subclasses / derived classes).
The concept of inheritance greatly enhances the ability to reuse code as well as
making design a much simpler and cleaner process.
The Object class is the highest superclass (ie. root class) of Java. All other
classes are subclasses (children) inherited from the Object class. The Object
class includes methods such as:
clone()
hashCode()
equals()
notify()
copy(Object src)
notifyAll()
finalize()
toString()
getClass()
wait()
Java uses the extends keyword to set the relationship between a parent class
and a child class.
As an example:
public class GraphicsBox extends Box
The GraphicsBox class assumes or inherits all the properties of the Box class
and can now add its own properties and methods as well as override existing
methods.
Overriding means: Creating a new set of method statements for the same
method signature (name, number of parameters and parameter types).
For example:
// define position locations
private int left, top;
// override a superclass method
public int displayVolume()
{
System.out.println(length*width*height);
System.out.println("Location: "+left+", "+top);
}
When extending a class constructor you can reuse the superclass constructor
and overridden superclass methods by using the reserved word super.
Note that this reference must come first in the subclass constructor.
The reserved word this is used to distinguish between the object's property
and the passed in parameter.
GraphicsBox(l,w,h,left,top)
{
super (l,w,h);
this.left=left;
this.top=top;
}
public void showObj()
{System.out.println(super.showObj()+"more stuff here");}
The reserved word this can also be used to reference private constructors
which are useful in initializing properties.
Special Note: You cannot override final methods, methods in final classes,
private methods or static methods.
Write a program to maintain the office database using single inheritance.
Superclass is Employee that contain the information as follows - Emp_code,
Emp_name, Address, Ph_no, Da-10%, Hra-20%. Create three subclass of
Manager, Typist, officer each class having their own basic pay & da,hra remain
same.
class employee
{
int empcode;
String empname, empadd;
int phno;
final static int da = 10;
final static int hra = 20;
int salary;
int basic;
employee ( )
{
empcode = phno = 0 ;
empname = empadd = "null";
}
employee (int c, int p, String n, String a)
{
empcode = c;
empname = n;
phno = p;
empadd = a;
}
void salary_comp ( )
{
salary = basic + (basic * da / 100) + (basic * hra / 100);
System.out.println ("NET SALARY" + salary);
}
}
class manager extends employee
{
manager (int c, int p, String n, String a, int b)
{
super (c, p, n, a);
basic = b;
}
manager ()
{
super ();
basic = 0;
}
}
class typist extends employee
{
typist (int c, int p, String n, String a, int b)
{
super (c, p, n, a);
basic = b;
}
typist ()
{
super ();
basic = 0;
}
}
//you need to code and add the subclass for Officer
import java.io.*;
class empInheritance
{
public static void main (String args[])
{
manager m = new manager (1, 9904567, "keshav", "kol", 15000);
typist t = new typist (30, 687900, "ram", "mum", 20000);
System.out.print ("MANAGER: ");
m.salary_comp ( );
System.out.print ("TYPIST: ");
t.salary_comp ( );
//add code to create an Officer object, of default value
//display the Officer object you created
}
}
this and super keywords
The two keywords, this and super to help you explicitly (clearly) name the field
or method that you want. Using this and super you have full control on whether
to call a method or field present in the same class or to call from the immediate
superclass.
this keyword is used as a reference to the current object which is an instance
of the current class. The keyword super also references the current object, but
as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local
variable hides, or shadows, a field with the same name. If a method needs to
pass the current object to another method, it can do so using the this
reference. Note that the this reference cannot be used in a static context, as
static code is not executed in the context of any object.
Example:
class Counter
{
int i = 0;
Counter increment()
{
i++;
return this;
}
void print()
{
System.out.println("i = " + i);
}
}
public class CounterDemo extends Counter
{
public static void main(String[] args)
{
Counter x = new Counter();
x.increment().increment().increment().print();
}
}
Abstract Classes
As seen from the previous example (Employee), the superclass is more general
than its subclass(es). The superclass contains elements and properties common
to all of the subclasses.
The previous example was of a concrete superclass that instance objects can be
created from. Often, the superclass will be set up as an abstract class which
does not allow objects of its prototype to be created. In this case, only objects
of the subclass are used. To do this the reserved word abstract is included in
the class definition.
Abstract methods are methods with no body specification. Subclasses must
provide the method statements for their particular meaning. If the method was
one provided by the superclass, it would require overriding in each subclass. And
if one forgot to override, the applied method statements may be inappropriate.
public abstract class Animal // class is abstract
{
private String name;
public Animal(String nm)
// constructor method
{ name=nm; }
public String getName()
// regular method
{ return (name); }
public abstract void speak(); // abstract method - note no {}
}
Abstract classes and methods force prototype standards to be followed (i.e.
they provide templates).
Interfaces
Interfaces are similar to abstract classes but all methods are abstract and all properties are
static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the
extends keyword is used for inheritance. Java does not allow multiple inheritance for classes
(i.e. a subclass being the extension of more than one superclass). An interface is used to tie
elements of several classes together. Interfaces are also used to separate design from coding
as class method headers are specified but not their bodies. This allows compilation and
parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit
testing frameworks.
As an example, we will build a Working interface for the subclasses of Animal. Since this
interface has the method called work(), that method must be defined in any class using the
Working interface.
public interface Working
{
public void work();
}
When you create a class that uses an interface, you reference the interface with the phrase
implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are
allowed. Any class that implements an interface must include code for all methods in the
interface. This ensures commonality between interfaced objects.
public class WorkingDog extends Dog implements Working
{
public WorkingDog(String nm)
{
super(nm); // builds ala parent
}
public void work() // this method specific to WorkingDog
{
speak();
System.out.println("I can herd sheep and cows");
}
}
Download