Unit-Ii Katakatkaka
Unit-Ii Katakatkaka
INHERITANCE
▪ In programming languages, inheritance means that the behavior and data associated
with child classes are always an extension of the properties associated with parent
classes.
▪ A child class will be given all the properties of a parent class and may in addition
define new properties.
▪ A child class is a more specialized form of the parent class. It is a contraction of the
parent type.
▪ Inheritance is always transitive so that a class can inherit features from super classes
many levels away.
▪ Subclasses can override behavior inherited from parent classes.
The term subclass refers to mechanics of constructing a new class using inheritance and is
easy to recognize from the source description of a program by the presence of the keyword
extends. The subtype relationship is more abstract, and is only loosely documented directly
by the program source. In the majority of situations a subclass is also a subtype.
BENEFITS OF INHERITANCE
1. Software Reusability:-
When behavior is inherited from another class, the code that provides that behavior
does not have to be rewritten. With object oriented techniques functions can be written
once and reused.
2. Increased Relaibility:-
Code that is executed frequently tends to have fewer bugs than code that is executed
infrequently. When the same components are used in two or more applications the code
will be exercised more than code that is developed for a single application. Thus, bugs in
such code tend to be discovered more quickly and latter applications gain the benefit of
using components that are more error free. Similarly the costs of maintenance of shared
components can be split among many projects.
3. Code sharing:-
Code sharing can occur on several levels with object oriented techniques. On one
level many users or projects can use the same classes. Another form of sharing occurs
when two or more classes developed by a single programmer as part of a project inherit
from a single parent class.
4. Consistency of Interface:-
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
When two or more classes inherit from the same super class we are assured that the
behavior they inherit will be the same in all cases. But behaves differently.
5. Software Components:-
6. Rapid Prototyping:-
8. Information hiding:-
To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword. To see how, let’s begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is
used to create a subclass of A.
Class A
{
int i, j;
void showij()
{ System.out.println("i and j: " + i + " " + j);
}
}
SUPER USES
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
Asubclass can call a constructor defined by its superclass by use of the following form of
super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass. super(
) must always be the first statement executed inside a subclass’ constructor.
class A
{
double width;
double height;
double depth;
A(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
A()
{
width = -1;
height = -1;
depth = -1;
}
A(double len)
{
width = height = depth = len;
}
double volume()
{
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
super.member.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
Here, member can be either a method or an instance variable. This second form of super
is most applicable to situations in which member names of a subclass hide members by the
same name in the superclass.
Example:-
class A
{
int i;
}
class B extends A
{
int i;
B(int a, int b)
{
super.i = a;
i = b;
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class C
{
public static void main(String args[])
{
B Ob = new B(1, 2);
Ob.show();
}
}
Output:-
i in superclass: 1
i in subclass: 2
MULTILEVEL HIERARCHY
Up to this point, we have been using simple class hierarchies that consist of only a
superclass and a subclass. However, you can build hierarchies that contain as many layers
of inheritance as you like. As mentioned, it is perfectly acceptable to use a subclass as a
superclass of another. For example, given three classes called A, B, and C, C can be a
subclass of B, which is a subclass of A. When this type of situation occurs, each subclass
inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of
B and A. To see how a multilevel hierarchy can be useful, consider the following program.
class A
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
{
int a,b;
A()
{
a=10;
b=20;
}
}
class B extends A
{
int c;
B(int x)
{
super();
c=x;
}
}
class C extends B
{
int d,sum;
C(int y,int z)
{
super(y);
d=z;
}
void addition()
{
sum=a+b+c+d;
System.out.println(“Addition is:”+ sum);
}
}
class Demo
{
public static void main(String args[])
{
C ob=new C(30,40);
ob.addition();
}
}
USING FINAL WITH INHERITANCE
To disallow a method from being overridden, specify final as a modifier at the start
of its declaration. Methods declared as final cannot be overridden.
Example:-
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
//It can’t be called causes an error.
Normally, Java resolves calls to methods dynamically, at run time. This is called late
binding. However, since final methods cannot be overridden, a call to one can be resolved
at compile time. This is called early binding.
class B extends A
{
// ERROR! Can't subclass A // ...
METHOD OVERRIDING
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
Definition:-
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its super class, then the method in the subclass is said to override
the method in the super class.
Note :- 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 super class will be hidden.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
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;
}
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show();}
}
Output: - k: 3
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
While the examples in the preceding section demonstrate the mechanics of method
overriding, they do not show its power. Indeed, if there were nothing more to method
overriding than a name space convention, then it would be, at best, an interesting curiosity,
but of little real value. However, this is not the case. Method overriding forms the basis for
one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method
dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism. Let’s begin by restating an important principle: a
superclass reference variable can refer to a subclass object. Java uses this fact to resolve
calls to overridden methods at run time. Here is how. When an overridden method is called
through a superclass reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. When different types of objects are referred to, different
versions of an overridden method will be called. In other words, it is the type of the object
being referred to (not the type of the reference variable) that determines which version of
an overridden method will be executed. Therefore, if a superclass contains a method that
is overridden by a subclass, then when different types of objects are referred to through a
superclass reference variable, different versions of the method are executed. Here is an
example that illustrates dynamic method dispatch:
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{ // override callme()
void callme()
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
ABSTRACT CLASSES
Thus, a subclass must override them—it cannot simply use the version defined in
the superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);
Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, we use the abstract keyword in front of the class keyword at the
beginning of the class declaration.
Note:-
❖ There can be no objects of an abstract class. That is, an abstract class cannot be
directly instantiated with the new operator.
❖ We cannot declare abstract constructors, or abstract static methods.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
❖ Any subclass of an abstract class must either implement all of the abstract methods
in the superclass, or be itself declared abstract.
abstract class A
{
abstract void show();
void display()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void show()
{
System.out.println("B's implementation of show");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.show();
b.display();
}
}
// Using abstract methods and classes.
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
double area()
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{
public static void main(String args[])
{
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
PACKAGES
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
❖ We can define classes inside a package that are not accessible by code outside that
package.
❖ We can also define class members that are only exposed to other members of the
same package.
Defining a Package:-
• Any classes declared within that file will belong to the specified package.
• The package statement defines a name space in which classes are stored.
• If we omit the package statement, the class names are put into the default package,
which has no name.
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
More than one file can include the same package statement. You can create a hierarchy of
packages.
• First, by default, the Java run-time system uses the current working directory as its
starting point.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
• Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
• Third, you can use the -classpath option with java and javac to specify the path to
your classes.
Example:-
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show( )
{
if(bal<0)
System.out.print(" ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[ ])
{
Balance b[ ] = new Balance[3];
b[0] = new Balance("padmaja", 125.50);
b[1] = new Balance("pramod", 155.75);
b[2] = new Balance("surya", 275.25);
for(int i=0; i<3; i++)
{
b[i].show( );
}
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file.
Make sure that the resulting .class file is also in the MyPack
directory.
Then execute the AccountBalance class, using the following command line:
java MyPack.AccountBalance
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
ACCESS PROTECTION
The three access specifiers - private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
A non-nested class has only two possible access levels: default and public.
If a class has default access, then it can only be accessed by other code within its
same package.
When a class is public, it must be the only public class declared in the file, and the
file must have the same name as the class.
IMPORTING PACKAGES
Java includes the import statement to bring certain classes, or entire packages, into
visibility. Once imported, a class can be referred to directly, using only its name. In a Java
source file, import statements occur immediately following the package statement (if it
exists) and before any class definitions.
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.).Finally, you specify either an
explicit classname or a star (*), which indicates that the Java compiler should import the
entire package.
Examples:-
import java.util.Date;
import java.io.*;
➢ All of the standard Java classes included with Java are stored in a package called
java.
➢ The basic language functions are stored in a package inside of the java package
called java.lang.
import java.lang.*;
It must be emphasized that the import statement is optional. Any place you use a class
name, you can use its fully qualified name, which includes its full package hierarchy. For
example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date
{
}
The same example without the import statement looks like this:
INTERFACES
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
To implement an interface, a class must create the complete set of methods defined by the
interface.
By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Defining an Interface:-
An interface is defined much like a class. This is the general form of an interface:
✓ When no access specifier is included, then default access results, and the interface
is only available to other members of the package in which it is declared.
✓ When it is declared as public, the interface can be used by any other code. In this
case, the interface must be the only public interface declared in the file, and the file
must have the same name as the interface.
✓ name is the name of the interface, and can be any valid identifier.
✓ They end with a semicolon after the parameter list. They are, essentially, abstract
methods; there can be no default implementation of any method specified within
an interface.
✓ Each class that includes an interface must implement all of the methods.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
✓ They are implicitly final and static, meaning they cannot be changed by the
implementing class.
✓ They must also be initialized. All methods and variables are implicitly public.
Example:-
interface Addition
{
public void add( );
}
class A implements Addition
{
int a,b;
A( )
{
a=10;
b=20;
}
public void add( )
{
System.out.println(a+b);
}
}
class B implements Addition
{
double a,b;
B( )
{
a=10;
b=20;
}
public void add( )
{
System.out.println(a+b);
}
}
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
class C
{
public static void main(String args[ ] )
{
A ob1=new A( );
ob1.add();
B ob2=new B( );
ob2.add( );
}
}
Note:- A class can implement more than one interface at a time.
Example:-
interface Addition
{
public void add( );
}
interface Multiplication
{
public void mul( );
}
class B
{
public static void main(String args[ ] )
{
A ob=new A( );
ob.add();
ob.mul( );
}
}
Nested Interfaces:-
▪ A nested interface can be declared as public, private, or protected. This differs from
a top-level interface, which must either be declared as public or use the default
access level, as previously described.
▪ When a nested interface is used outside of its enclosing scope, it must be qualified
by the name of the class or interface of which it is a member.
▪ Thus, outside of the class or interface in which a nested interface is declared, its
name must be fully qualified.
One interface can inherit another by use of the keyword extends. The syntax is the same
as for inheriting classes.
Note:- When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
interface A
{
void meth1( );
void meth2( );
}
interface B extends A
{
void meth3( );
}
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II
the contract
defined.