0% found this document useful (0 votes)
7 views23 pages

Unit-Ii Katakatkaka

Uploaded by

siddeshkosme143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views23 pages

Unit-Ii Katakatkaka

Uploaded by

siddeshkosme143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

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:-

Inheritance enables programmers to construct reusable software components. The


goal is to permit the development of new applications that require little or no actual coding.
The java library offers a rich collection of software components for use in the development
of applications.

6. Rapid Prototyping:-

When a software system is constructed largely out of reusable components,


developers can concentrate their time on understanding the new and unusual portion of the
system. Thus software systems can be generated more quickly and easily leading to a style
of programming known as rapid prototyping or exploratory programming.

7. Polymorphism and Frameworks:-

Polymorphism in programming languages permits the programmer to generate high


level reusable components that can be tailored to fit different applications by changes in
their low level parts. The java AWT is an example of a large software framework.

8. Information hiding:-

A programmer who reuses a software component needs only to understand the


nature of the component and its interface. It is not necessary for the programmer to have
detailed information concerning matters such as the techniques use to implement the
component. Thus the interconnectedness between software systems is reduced.

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.

// A simple example of inheritance.


// Create a superclass.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

Class A
{
int i, j;
void showij()
{ System.out.println("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


Class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B(); // The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println(); /* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The output from this program is shown here:
Contents of superOb: i and j: 10 20
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

Contents of subOb: i and j: 7 8 k: 9


Sum of i, j and k in subOb: i+j+k: 24

SUPER USES

Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.

super has two general forms.


• The first calls the superclass’ constructor.
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass.

Using super to Call Superclass Constructors:-

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

return width * height * depth;


}
}
class B extends A
{
double weight;
B(double w, double h, double d, double m)
{
super(w, h, d);
weight = m;
}
B()
{
super();
weight = -1;
}
B(double len, double m)
{
super(len);
weight = m;
}
}
class Demo
{
public static void main(String args[])
{
B b1 = new B(10, 20, 15, 34.3);
B b2 = new B();
B b3 = new B(3, 2);
double vol;
vol = b1.volume();
System.out.println("Volume of b1 is " + vol);
vol = b2.volume();
System.out.println("Volume of b2 is " + vol);
vol = b3.volume();
System.out.println("Volume of b3 is " + vol);
}
}

A Second Use for super:-

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

The keyword final has three uses.


▪ Using final to create a constant.
▪ Using final to prevent Overriding
▪ Using final to prevent Inheritance
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

Using final to create a constant:-


A variable can be declared as final. Doing so prevents its contents from being
modified.
This means that we must initialize a final variable when it is declared.
Example:-
final int PRIORITY=15;
It is a common coding convention to choose all uppercase identifiers for final variables.

Using final to Prevent Overriding:-

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.

Using final to Prevent Inheritance:-

❖ Declaring a class as final implicitly declares all of its methods as final.


final class A
{
// ... }
// The following class is illegal.

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

DYNAMIC METHOD DISPATCH

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:

// Dynamic Method Dispatch


class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}

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

A r; // obtain a reference of type A

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

We require that certain methods be overridden by subclasses by specifying the


abstract type modifier. These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified in the superclass.

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

❖ Packages are containers for classes.

❖ The package is both a naming and a visibility control mechanism.

❖ 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:-

• To create a package include a package command as the first statement in a Java


source file.

• 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.

This is the general form of the package statement:


package pkg;

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.

The general form is


package pkg1[.pkg2[.pkg3]];

Finding Packages and CLASSPATH:-

• 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

Java addresses four categories of visibility for class members:

• Subclasses in the same package


• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses

The three access specifiers - private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.

❖ Anything declared public can be accessed from anywhere.


❖ Anything declared private cannot be seen outside of its class.
❖ When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package. This is the default
access.
❖ If you want to allow an element to be seen outside your current package, but only
to classes that subclass your class directly, then declare that element protected.

A non-nested class has only two possible access levels: default and public.

When a class is declared as public, it is accessible by any other code.

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.

Private No Modifier Protected Public

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes


subclass

Same package No Yes Yes Yes


non-subclass

Different No No Yes Yes


Package subclass

Different Package No No No Yes


non-subclass
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

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.

This is the general form of the import statement:


import pkg1[.pkg2].(classname|*);

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.

➢ It is implicitly imported by the compiler for all programs.

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:

class MyDate extends java.util.Date


{
}
In this version, Date is fully-qualified.
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

INTERFACES

Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.

Once it is defined, any number of classes can implement an interface.

Note:- One class can implement any number of interfaces.

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:

access interface name


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

✓ 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.

✓ Notice that the methods that are declared have no bodies.

✓ 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

✓ Variables can be declared inside of interface declarations.

✓ 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 A implements Addition, Multiplication


{
int a,b;
A( )
{
a=10;
b=20;
}
public void add( )
{
System.out.println(a+b);
}
public void mul( )
{
System.out.println(a*b);
}
}
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

class B
{
public static void main(String args[ ] )
{
A ob=new A( );
ob.add();
ob.mul( );
}
}

Nested Interfaces:-

▪ An interface can be declared a member of a class or another interface. Such an


interface is called a member interface or a nested interface.

▪ 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.

Interfaces Can Be Extended:-

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

class MyClass implements B


{
public void meth1( )
{
System.out.println("Implement meth1.");
}
public void meth2( )
{
System.out.println("Implement meth2.");
}
public void meth3()
{
System.out.println("Implement meth3.");
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

DIFFERENCES BETWEEN A CLASS AND AN INTERFACE

Property Class Interface

Instantiation Can Be Can not be


Instantiated instantiated

State Each Object Each objected


created will have created after
its own state implementing
will have the
same state

Behavior Every Object Every Object


will have the will have to
same behavior define its own
unless behavior by
overridden. implementing
FUNDAMENTALS OF JAVA ( III –II ECE) UNIT – II

the contract
defined.

Inheritance A Class can An Interface


inherit only one cannot inherit
Class and can any classes
implement many while it can
interfaces extend many
interfaces

Variables All the variables All the variables


are instance by are static final
default unless by default, and a
otherwise value needs to
specified be assigned at
the time of
definition

Methods All the methods All the methods


should be having are abstract by
a definition default and they
unless decorated will not have a
with an abstract definition.
keyword

You might also like