Inheritance
Learning Objective
Welcome to the Day2 in Java. Here we would concentrate on solving Inheritance Problems.
- Inheritance
- Member Access & Inheritance
- Using Super
- Method Overriding
- Dynamic Method Dispatch
- Inner Classes
Orientation Video
Introduction
Inheritance:
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. In Java, inheritance is used for two purposes:
1. Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance.
2. Interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of subtyping. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance. In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements.
public class derived-class-name extends base-class-name {
// derived class methods extend and possibly override
// those of the base class
}
public class class-name implements interface-name {
// class provides an implementation for the methods
// as specified by the interface
}
Using Super:
The super is a keyword defined in the java programming language.
• The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.
• The super keyword as a standalone statement is used to call the constructor of the superclass in the base class.
Example to use the super keyword to call the constructor of the superclass in the base class:
public class Class1{
public Class1(String arg){
super(arg);
}
• super.() is the syntax used to give a call to a method of the superclass in the base class.
• This kind of use of the super keyword is only necessary when we need to call a method that is overridden in this base class in order to specify that the method should be called on the superclass.
Method Overiding :
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here: k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the versio n of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass' version. This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ). Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded.
Dynamic Method Dispatch:
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. For example:
class Try {
void disp() {}
}
class Test extends Try {
void disp() {}
public static void main(String args[]){
Try t=new Try();
Test t1=new Test();
Try v;
v=t1;
v.disp(); // call to the disp() method from Test.
}
}
Here, the Test version of the disp() method is called because the reference variable v of the type Try points to the Test object t1.
Inner Classes:
In Java it is possible to define one class inside another. A class defined inside another one is called an inner class. Inner classes cannot have static members. only static final variables.
Interfaces are never inner.
Static classes are not inner classes.
Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces are always implicitly static so they are never considered to be inner classes.A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement.
Resources
Books
- Java Complete Reference
- Thinking in Java
//1. Anonymous.java
interface type1 { void hi(); void hello(); } abstract class type2 { abstract void hi(); abstract void hello(); } class Anonymous { public static void main(String[] args) { Anonymous an=new Anonymous(); an.check(); } public void check() { type1 t1=new type1(){ public void hi() { System.out.println("type1 Hi method"); } public void hello() { System.out.println("type1 Hello method"); } }; type2 t2=new type2(){ public void hi() { System.out.println("type2 Hi method"); } public void hello() { System.out.println("type2 Hello method"); } }; t1.hi();t1.hello(); t2.hi();t2.hello(); } }
//2.Argument.java
class Argument
{
int x=10;
public static void main(String[] args)
{
Argument a=new Argument();
System.out.println("value of x before passing value= " + a.x);
a.arg(a.x);
System.out.println("value of x after passing value= " + a.x+"\n\n\n\n");
System.out.println("value of x before passing reference= " + a.x);
a.arg(a);
System.out.println("value of x after passing reference= " + a.x+"\n\n\n\n");
Argument a1;
a1=a.arg1(a);//taking returning object from method
}
public void arg(int x)//pass by value
{
x++;
}
public void arg(Argument a)//pass by reference
{
a.x++;
}
public Argument arg1(Argument a)//metod returning object
{
return a;
}
}
//3.Constructor Overloadingclass Constructoverld
{
public static void main(String[] args)
{
Constructoverld ov=new Constructoverld();
Constructoverld ov1=new Constructoverld(10);
}
public Constructoverld()
{
System.out.println("Constrcutor with no arguments");
}
public Constructoverld(int i)
{
System.out.println("Constrcutor with one integer "+i);
}
}
//4. outer
class Outer
{
private String out="private Outer class variable";
public Outer()
{
System.out.println("Outer object is nesessary to create inner class object always.");
System.out.println("Outer Class object created");
}
class Inner
{
String inn="Inner class variable";
public void innermeth()
{
System.out.println("Inner method accessing "+inn);
System.out.println("Inner method accessing "+out);
}
public Inner()
{
System.out.println("Inner Class object created outside of Outer class");
}
}
}
class Outer1
{
public static void main(String[] args)
{
Outer o=new Outer();
Outer.Inner inn=o.new Inner();
inn.innermeth();
}
}
//5. outer
class Outer
{
private String out="private Outer class variable";
public static void main(String[] args)
{
Outer o=new Outer();
o.outermeth();
}
public Outer()
{
System.out.println("Outer Class object created");
}
public void outermeth()
{
System.out.println("Outer method creating inner class object");
Inner in=new Inner();
System.out.println("Outer method accessing inner method");
in.innermeth();
}
class Inner
{
String inn="Inner class variable";
public void innermeth()
{
System.out.println("Inner method accessing "+inn);
System.out.println("Inner method accessing "+out);
}
public Inner()
{
System.out.println("Inner Class object created");
}
}
}
//6.Overload
class Overload
{
public static void main(String[] args)
{
Overload ov=new Overload();
ov.myMethod();
ov.myMethod(10);
}
public void myMethod()
{
System.out.println("Method with no arguments");
}
public void myMethod(int i)
{
System.out.println("Method with one integer "+i);
}
//public int myMethod(int i){System.out.println("Method with one integer "+i);return i;}
//the above line leads to a compile time error.
}
//7.Recursion
class Recursion
{
public static void main(String[] args)
{
Recursion r=new Recursion();
System.out.println("Factorial of 5 is "+r.fact(5));
//System.out.println("Factorial of 5 is "+r.facterr(5));
//calling method with logical error.there is no condition to end method.
}
public int fact(int x)
{
if(x>1)
return x*fact(x-1);
else
return 1;
}
public int facterr(int x)//method with logical error.
{
return x*facterr(x-1);
}
}
http://www.faqs.org/docs/javap/c8/s3.html
Task1 Description :
Create a class LIST which represents a generalized list (By a sequential implementation) where insertions and deletions can be done arbitrarily at any point in the list. Implement all basic operations on it. (Insert, Delete, Isempty, Display etc). Specialize this class to represent STACK data structure (By inheriting the List class) and implement all basic operations (push, pop, Isempty, Display), on it.
Task2 Description :
Create a Java class point (x,y) with x and y coordinate. Create a line class by inheriting the point class. The line class has two points ((x1, y1), (x2, y2)) has a method length (). Create triangle class by inheriting line class. The triangle class has three lines or sides ( [(x1,y1),(x2,y2)], [(x2,y2),(x3,y3)] , [(x3,y3),(x1,y1)] ) , type ( right angular, equilateral) of type enum , and a method to find the area() by using suitable equation for the type of triangular.. Instantiate the line and triangle classes with suitable data and print the line length and triangle area.
Task3 Description
Inner classes
Write a inner class with methods to convert temperatures between Celsius and Fahrenheit in both directions. The declaration of temperature variables, reading of their values, invoking the conversion methods should be specified in an outer class.
Comments
Post a Comment