0% found this document useful (0 votes)
7 views

Java Unit-2

Uploaded by

23wj1a05m1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Unit-2

Uploaded by

23wj1a05m1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-II

Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it allows the
creation of hierarchical classifications. Using inheritance, we can create a general class that defines
traits common to a set of related items. This class can then be inherited by other, more specific
classes, each adding those things that are unique to it.

In the terminology of Java, a class that is inherited is called a superclass. The class that does the
inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It
inherits all of the members defined by the superclass and adds its own, unique elements.

Types of inheritance
1.Single Inheritance
2.Multilevel Inheritance
3.Hirarchical Inheritance
4.Hybrid Inheritance
5.Multiple Inheritance

Inheritance Basics
To inherit a class, 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.

//creates a superclass
class A
{
int i,j;
void showij()
{
System.out.println("i and j"+i+" "+j);
}
}
//creates a subclass by extending class A
class B extends A
{
int k;
void showk()
{
System.out.println("k is"+ k);
}
void sum()
{
System.out.println("the i+j+k is"+(i+j+k));
}
}
public class Simplein
{
public static void main(String[]args)
{
A obj=new A();
B obj1=new B();
obj.i=10;
obj.j=20;
obj.showij();
obj1.i=5;
obj1.j=6;
obj1.k=7;
obj1.showk();
obj1.sum();
}
}

Member access rules


Although a subclass includes all of the members of its superclass, it cannot access those members
of the superclass that have been declared as private. For example, consider the following simple
class hierarchy:

class A
{
int i;
private int j;
void setij(int x,int y)
{
i=x;j=y;
}
}
class B extends A
{
int total;
void sum()
{
total=i+j;// j is not accessible here
}
}

Another Example

class box
{
double wdt;
double hgt;
double dep;
box(box ob)
{
wdt=ob.wdt;
hgt=ob.hgt;
dep=ob.dep;
}
box(double w,double h,double d)
{
wdt=w;hgt=h;dep=d;
}
box()
{
wdt=-1;hgt=-1;dep=-1;
}
box(double len)
{
wdt=hgt=dep=len;
}
double volume()
{
return wdt*hgt*dep;
}
}
class boxwgt extends box
{
double wgt;
boxwgt(double w,double h,double d,double m)
{
wdt=w;hgt=h;dep=d;wgt=m;
}
}
public class Demowgt
{
public static void main(String[]args)
{
boxwgt obj=new boxwgt(10,20,15,34.3);
boxwgt obj1=new boxwgt(2,3,4,0.076);
double vol;
vol=obj.volume();
System.out.println("the volume is"+vol);
System.out.println("the weight is "+obj.wgt);

vol=obj1.volume();
System.out.println("the volume is"+vol);
System.out.println("the weight is"+obj1.wgt);
}
}

A Superclass Variable Can Reference a Subclass Object

public class Demowgt


{
public static void main(String[]args)
{
boxwgt weightbox =new boxwgt(10,20,15,34.3);
box plainbox =new box();
double vol;
vol= weightbox.volume();
System.out.println("the volume is"+vol);
System.out.println("the weight is "+ weightbox.wgt);

plainbox = weightbox;
vol= plainbox.volume();
System.out.println("the volume is"+vol);
System.out.println("the weight is"+ plainbox.wgt);
}
}

Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects.
Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the
weightbox object.It is important to understand that it is the type of the reference variable—not the
type of the object that it refers to—that determines what members can be accessed.

That is, when a reference to a subclass object is assigned to a superclass reference variable, you
will have access only to those parts of the object defined by the superclass. This is why plainbox
can’t access weight even when it refers to a BoxWeight object. If you think about it, this makes
sense, because the superclass has no knowledge of what a subclass adds to it. This is why the last
line of code in the preceding fragment is commented out. It is not possible for a Box reference to
access the weight field, because Box does not define one.

Using super
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.

A subclass 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.

The first calls the superclass’ constructor example


class room
{
int len,bre;
room(int x,int y)
{
len=x;bre=y;
}
int area()
{
return len*bre;
}
}
class bedroom extends room
{
int hgt;
bedroom(int x,int y,int z)
{
super(x,y);
hgt=z;
int volume()
{
return len*bre*hgt;
}
}
public class Inhertese
{
public static void main(String[]args)
{
bedroom obj=new bedroom(10,20,30);
int a=obj.area();
int v =obj.voume();
System.out.println(a+” ”+v);
}
}

A Second Use for super

class a
{
int i;
}
class b extends a
{
int i;
b(int x,int y)
{
super.i=x;
i=y;
}
void show()
{
System.out.println(super.i);
System.out.println(i);
}
}

public class Usesuper {


public static void main(String[]args)
{
b obj=new b(1,2);
obj.show();
}
}

class a
{
void methoda()
{
System.out.println("Class a method");
}
}
class b extends a
{
void methodb()
{
System.out.println("class b method");
}
}
class c extends b
{
public void methodc()
{
System.out.println("class c method");
}
public static void main(String args[])
{
c obj = new c();
obj.methoda(); //calling grand parent class method
obj.methodb(); //calling parent class method
obj.methodc(); //calling local method
}
Hierarchical Inheritance

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
}
}

Hybrid Inheritance :-

class a
{
void display()
{
System.out.println("the class a");
}
}
class b extends a
{
void display()
{
System.out.println("the class b");
}
}
class c extends a
{
void display()
{
System.out.println("the class c");
}
}

class d extends b
{
void display()
{
System.out.println("the class d ");
}
}
public class Hybriddemo
{
public static void main(String[]args)
{
d obj=new d();
obj.display();
}
}

Method Overriding: when 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 its subclass.

class a
{
int i,j
a(int a,int b)
{
i=a;j=b;
}
void show()
{
System.out.println(“i and j are”+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(“i and j are”+i+””=j);
}
}
class Override
{
public static void main(String[]args)
{
b obj=new obj(10,20,30);
obj.show();
}

Calling the superclass method

Class a
{
Int i,j
A(int a,int b)
{
I=a;j=b;
}
Void show()
{
System.out.println(“i and j are”+i+””=j);
}
Class b extends a
{
Int k;
B(int a,int b,int c)
{
Super(a,b);
K=c;
}
Void show()
{
Super.show();
System.out.println(“k is”+k);
}
}
Class Override
{
Public static void main(String[]args)
{
B obj=new obj(10,20,30);
Obj.show();
}

class fig
{
double d1,d2;
fig(double a,double b)
{
d1=a;d2=b;
}
double area()
{
System.out.println("this is super class");
return 0;
}

}
class rect extends fig
{
rect(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in rect");
return d1*d2;
}
}
class triangle extends fig
{
triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in triangle");
return d1+d2;
}
}
public class Rp
{
public static void main(String[]args)
{
fig obj=new fig(1,2);
rect obj1=new rect(3,4);
triangle obj2=new triangle(5,6);
fig r ;
r=obj1;
r.area();
r=obj2;
r.area();
r=obj;
r.area();

}
}

Dynamic method dispatch


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.

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.
class a
{
void callme()
{
System.out.println("inside A's callme method");
}
}
class b extends a
{
void callme()
{
System.out.println("inside B's callme method");
}
class c extends a
{
void callme()
{
void callme()
{
System.out.println("inside C's callme method");
}
}
public class Dispatch
{
public static void main(String[]args)
{
a obj=new a();
b obj1=new b();
c obj2=new c();
a r;
r=obj;
r.callme();
r=obj1;
r.callme();
r=obj2;
r.callme();
}
}

Abstract classes and methods

abstract class a
{
abstract void call();

void callme()
{
System.out.println("the super class");
}

}
class b extends a
{
void call()
{
System.out.println("the class b");
}
}
public class Ae
{
public static void main(String[]args)
{
b obj1=new b();
obj1.call();
obj1.callme();
}
}

class fig
{
double d1,d2;
fig(double a,double b)
{
d1=a;d2=b;
}
double area()
{
System.out.println("this is super class");
return 0;
}

}
class rect extends fig
{
rect(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in rect");
return d1*d2;
}
}
class triangle extends fig
{
triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in triangle");
return d1+d2;
}
}
public class Rp
{
public static void main(String[]args)
{
fig obj=new fig(1,2);
rect obj1=new rect(3,4);
triangle obj2=new triangle(5,6);
fig r ;
r=obj1;
r.area();
r=obj2;
r.area();
r=obj;
r.area();

}
}

Using Abstract classes


There are situations in which you want to define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every method. That is, sometimes you
want to create a superclass that only defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of
the methods that the subclasses must implement. One way this situation can occur is when a
superclass is unable to create a meaningful implementation for a method.

This is the case with the class Figure used in the preceding example. The definition of area( ) is
simply a
placeholder. It will not compute and display the area of any type of object. One way, as shown in
the previous
example, is to simply have it report a warning message. While this approach can be useful in
certain situations—such as debugging—it is not usually appropriate. You may have methods that
must be overridden by the subclass in order for the subclass to have any meaning. Consider the
class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure
that a subclass does, indeed, override all necessary methods. Java’s solution to this problem is the
abstract method

To declare an abstract method, use this general form:

abstract type name(parameter-list);

use the abstract keyword in front of the class keyword at the beginning of the class declaration.
There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated
with the new operator.

abstract class a
{
abstract void call();

void callme()
{
System.out.println("the super class");
}

}
class b extends a
{
void call()
{
System.out.println("the class b");
}
}
public class Ae
{
public static void main(String[]args)
{
b obj1=new b();
obj1.call();
obj1.callme();
}
}

Example for Abstract classes and methods

abstract class fig


{
double d1,d2;
fig(double a,double b)
{
d1=a;d2=b;
}
abstract double area();

}
class rect extends fig
{
rect(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in rect");
return d1*d2;
}
}
class triangle extends fig
{
triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("the area in triangle");
return d1+d2;
}
}
public class Rp
{
public static void main(String[]args)
{
rect obj1=new rect(3,4);
triangle obj2=new triangle(5,6);
fig r ;
r=obj1;
r.area();
r=obj2;
r.area();

}
}
Using final with inheritance
The keyword final has three uses.
First, it can be used to create the equivalent of a named constant. Ex:--final int x=30;
Second it can be used to Prevent Overriding
Third one to prevent inheritance .

Example to prevent overriding ;-


While method overriding is one of Java’s most powerful features, there will be
times when you will want to prevent it from occurring. 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
class a
{
final void add()
{
System.out.prinln("this is final method");
}
}
class b extends a
{
void add() //ERROR:can't override method .
{
System.out.println("second class");
}
}
Example to prevent inheritance :-
Sometimes you will want to prevent a class from being inherited. To do this,
precede the class declaration with final. Declaring a class as final implicitly
declares all of its methods as final, too.

final class a
{
final void add()
{
System.out.prinln("this is final method");
}
}
class b extends a //ERROR:can’t inherit the class
{
void add() //ERROR:can't override.
{
System.out.println("second class");
}
}

The Object Class


There is one special class, Object, defined by Java. All other classes are subclasses
of Object. That is, Object is a superclass of all other classes. This means that a
reference variable of type Object can refer to an object of any other class. Also, since
arrays are implemented as classes, a variable of type Object can also refer to any
array.

Object defines the following methods, which means that they are available in every
object.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You
may override the others. However, notice two methods now: equals( ) and toString(
). The equals( ) method compares two objects. It returns true if the objects are
equal,and false otherwise. The precise definition of equality can vary, depending on
the type of objects being compared. The toString( ) method returns a string that
contains a description of the object on which it is called.

Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface
must implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

interface a
{
void add();
}
interface b
{
void mul();
}

class c implements a,b


{
public void add()
{
System.out.println("this is first interface explonations");
}
public void mul()
{
System.out.println("this is 2nd interface explonations");
}
}
public class Ex
{
public static void main(String[]args)
{
c obj=new c();
obj.add();
obj.mul();
}
}
Packages :-
Packages are containers for classes. They are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into
new class definitions.

Through the use of the interface keyword, Java allows you to fully abstract an interface from its
implementation. Using interface, you can specify a set of methods that can be implemented by one
or more classes.

Defining a Package
To create a package is quite easy: simply 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 you omit the package
statement, the class names are put into the default package, which has no name. While the default
package is fine for short, sample programs, it is inadequate for real applications. Most of the time,
you will define a package for your code.
This is the general form of the package statement:
package pkg;

Ex: package mypackage

Accessing Packages

The pack1 contains the class as emp1

package pack1;
class emp
{
public void add()
{
System.out.println("parent class");

}
}
public class emp1 extends emp
{
public void mul()
{
System.out.println("child class");
}
}

The Faculty class represents the outside the package,now access the emp1 content to the outside
package.

import pack1.*;

public class Faculty


{
public static void main(String[]args)
{
emp1 obj=new emp1();
obj.mul();
obj.add();
}

o/p:---
second class
parent class

importing packages

In this diagram employee and empinfo are two


packages
Open the employee package and create the classes
and interfaces shown in the below diagram
package employee;

public class empno


{
int eno;
public void enumber(int x)
{
eno=x;
}
public void show()
{
System.out.println("the emp no is"+eno);
}
}

package employee; //interface

public interface salary


{
void sal(int b);
}

package employee;
public class empname extends empno implements salary
{
String s;
int k;
public void sal(int b)
{
k=b;
}
public void getstring(String d)
{
s=d;
}
public void show1()
{
System.out.println("the name is"+s);
System.out.println("the salary is "+k);
}
}

Next open the package empinfo and create one class named Info and type the code to call the
package employee

package empinfo;
import employee.*;

public class Info


{
public static void main(String[]args)
{
empname obj=new empname();
obj.enumber(10);
obj.show();
obj.sal(10000);
obj.getstring("donald");
obj.show1();
}
}
o/p: the emp no is10
the name isdonald
the salary is 10000

The class member access rules in the packages

You might also like