75
Inheritance Java supports inheritance by allowing one class to incorporate another class into its declaration.

Inheritance and package.pdf

Embed Size (px)

Citation preview

Page 1: Inheritance and package.pdf

InheritanceJava supports inheritance by allowing one class to incorporate another class into its

declaration.

Page 2: Inheritance and package.pdf

class A{

int i, j;

void show(){

System.out.println(“i=“ + i + “j=“ +j);

}

}

class B extends A{

int k;

void show1(){

System.out.println(“k=“ + k);

}

void sum(){

System.out.println(“i+j+k=“ +( i+j+k));

}

}

Page 3: Inheritance and package.pdf

Inheritance Cont..

class mainclass{

public static void main(String args[])

{

B ob2=new B();

ob2.i=10;

ob2.j=20;

ob2.k=30;

ob2.show(); //?

ob2.show1();//?

ob2.sum();//?

}

}

Page 4: Inheritance and package.pdf

Inheritance Cont..

class mainclass{

public static void main(String args[])

{

B ob2=new B();

ob2.i=10;

ob2.j=20;

ob2.k=30;

ob2.show();//i=10 j=20

ob2.show1();// k=30

ob2.sum();//60

}

}

Page 5: Inheritance and package.pdf

Constructor called

class A{

A(){

}

}

Class B extends A{

B(){

}

}

class mainconst{

public static void main(String args[ ]){

B ob=new B();

}

}

Page 6: Inheritance and package.pdf

Using Super

• A subclass can call a constructor defined by its

superclass by use of the following form of

SUPER.

• super(parameter-list)

• parameter-list specifies any parameters needed

by the constructor in the superclass. Super()

must always be the first statement executed

inside a subclass constructor.

Page 7: Inheritance and package.pdf

Illustration of super

public class base {

private int i;

private int j;

base(int a,int b){

i=a;

j=b;

}

void show()

{

System.out.println("i:" +i +"j:" +j);

}

}

Page 8: Inheritance and package.pdf

Illustration of super

public class derived extends base {

int k;

derived(int a,int b)

{

super(a,b);

k=b;

}

void show1()

{

show();

System.out.println("k:" +k);

} }

Page 9: Inheritance and package.pdf

Illustration of super

public class Inheritance {

public static void main(String[] args) {

derived d=new derived(11,22);

d.show1();

}

}

Page 10: Inheritance and package.pdf

A second use for super

class first{

int i;

}

class second extends first

{ int i;

second(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);

}

}

Page 11: Inheritance and package.pdf

A second use for super

class example{

Public static void main(String args[])

{

second subobj =new second(1,2);

Subobj.show();

}

}

Page 12: Inheritance and package.pdf

Creating Multilevel Hierarchy

person

Name,code

admin

Experience

salary

Name,code,experience,Pay()

Page 13: Inheritance and package.pdf

Method Overriding

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

Page 14: Inheritance and package.pdf

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);

}

}

Page 15: Inheritance and package.pdf

class override{

public static void main(string args[]){

B subob=new B(1,2,3);

subob.show();

}

}

Page 16: Inheritance and package.pdf

class override{

public static void main(string args[]){

B subob=new B(1,2,3);

subob.show();

}

}

Output:

K:3

Page 17: Inheritance and package.pdf

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:” +k);

}

}

Page 18: Inheritance and package.pdf

Output:

i and j:1 2

K:3

Page 19: Inheritance and package.pdf

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(int m ){

k=m

System.out.println(“k:” +k);

}

}

Page 20: Inheritance and package.pdf

class override{

public static void main(string args[]){

B subob=new B(1,2,3);

subob.show();

}

}

Page 21: Inheritance and package.pdf

Output:

i and j:1 2

K:3

• 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

Page 22: Inheritance and package.pdf

Using Abstract classes

• Sometimes certain methods be overridden by subclasses by specifying the abstract

type modifier. These methods are referred to as subclass responsibility because they

have no implementation specified in the superclass. Thus a subclass must override

them.

• General form:

• abstract type name (parameter-list);

• No method body is present.

• Any class that contains one or more abstract methods must also be declared

abstract.

• No object for abstract class i.e an abstract class cannot be directly instantiated with

new operator.

• Any subclass of an abstract class must either implement all of the abstract methods

in the superclass, or be itself declared abstract.

Page 23: Inheritance and package.pdf

Abstract class

abstract class A{

abstract void one();

}

class B extends A{

void one(){

system.out.println(“ abstract class implementation”);} }

class demo{

public static void main(String args[])

{

B b=new B();

b.one();}

}

Page 24: Inheritance and package.pdf

Using Final With Inheritance

• Using final to prevent overridingClass a{

final void math1(){

------

}

}

Class b extends a{

Void meth1()//Error

{

---

--}

}

Page 25: Inheritance and package.pdf

Using Final With Inheritance

• Using final to prevent inheritancefinal class a{

}

Class b extends a{ //error

}

Page 26: Inheritance and package.pdf

Programs

• An educational institution wishes to maintain a

database of its employees. The database is

divided into a number of classes whose

hierarchical relationships are shown in Fig. 1.

The figure also shows the minimum

information required for each class. Specify all

the classes and define methods to create the

database and retrieve individual information as

and when required.

Page 27: Inheritance and package.pdf

Figure 1

Staff

Code

Name

teacher

Subject

publication

Officer

grade

typist

Speed

Page 28: Inheritance and package.pdf

Program 2

• Design a class to represent a bank account . Include the

following members.

Data members

• Name of the depositor

• Account number

• Type of account

• Balance amount in the account

Methods

• To assign initial values

• To deposit an amount

• To withdraw an amount after checking balance

• To display the name and balance

Page 29: Inheritance and package.pdf

Program 3

• Assume that a bank maintains two kinds of account for its

customers, one called savings account and the other current

account. The savings account provides compound interest and

withdrawal facilities but no cheque book facility. The current

account provides cheque book facility but no interest. Current

account holders should also maintain a minimum balance and

if the balance falls below this level, a service charge is

imposed

• Create a class Account that stores customer name, account

number and type of account. Form this derive the classes Curr-

acct and Sav-acct to make them more specific to their

requirements include the necessary methods in order to

achieve the following tasks:

Page 30: Inheritance and package.pdf

Program 3

• Accept deposit from a customer and update the

balance.

• Display the balance.

• Compute and deposit interest.

• Permit withdrawal and update the balance.

• Check for the minimum balance, impose

penalty, if necessary and update the balance.

• Use constructors .

Page 31: Inheritance and package.pdf

Interfaces

• Interfaces are syntactically similar to classes,

but they lack instance variables, and their

methods are declared without any body.

Page 32: Inheritance and package.pdf

Interfaces

interface name{

Return_type methodname1(parameter list);

Return_type methodname2(parameter_list);

……………………………………………………………………

……………………………………………………………………

Type variable name1=value;

Type variable name2=value;

………………………………………….

}

Page 33: Inheritance and package.pdf

• Method are declared inside interface.

• Variables are final and static.

Page 34: Inheritance and package.pdf

Implementing interface

• class classname [extends superclass]

[implements interfacename1, interfacename2]

Page 35: Inheritance and package.pdf

Program 1

interface interface1{

int v=10;

void show();

}

class B implements interface1{

public void show() {

System.out.println(v); }

}

class testing

{

public static void main(String args[]){

B ob1=new B();

ob1.show(); //O/P?

}

}

Page 36: Inheritance and package.pdf

Program 1

interface interface1{

int v=10;

void show();

}

class B implements interface1{

public void show() {

System.out.println(x); }

}

class testing

{

public static void main(String args[]){

B ob1=new B();

ob1.show(); //O/P:10

}

}

Page 37: Inheritance and package.pdf

Program 2

interface interface1{

int v=10;

void show();

}

class B implements interface1{

public void show() {

v=v+10;

System.out.println(v); }

}

class testing

{

public static void main(String args[]){

B ob1=new B();

ob1.show(); //O/P?

}

}

Page 38: Inheritance and package.pdf

Program 2

interface interface1{

int v=10;

void show();

}

class B implements interface1{

public void show() {

v=v+10;// ERROR

System.out.println(x); }

}

class testing

{

public static void main(String args[]){

B ob1=new B();

ob1.show(); //O/P: ERROR

}

}

Page 39: Inheritance and package.pdf

Program 3

interface interface1{

int v=10;

void show();

}

interface interface2{

int x=20;

void show(); }

class B implements interface1, interface2 {

public void show() {

System.out.println(v + " " +x); } }

class testing {

public static void main(String args[]){

B ob1=new B();

ob1.show(); } }

Page 40: Inheritance and package.pdf

Program 3

interface interface1{

int v=10;

void show();

}

interface interface2{

int x=20;

void show(); }

class B implements interface1, interface2 {

public void show() {

System.out.println(v + " " +x); } }

class testing {

public static void main(String args[]){

B ob1=new B();

ob1.show(); } }

Page 41: Inheritance and package.pdf

Program 4interface data {

int x=0;

double y=2.3; }

interface functions extends data {

void getdata(); }

class test implements functions{

public void getdata() {

System.out.println(x + " " +y);}}

class interfaceex {

public static void main(String args[]){

test ob1=new test();

ob1.getdata(); }}//O/P:0,2.3

Page 42: Inheritance and package.pdf

Program 5interface data {

int x=0;

double y=2.3;

void setdata(); }

interface functions extends data {

void getdata(); }

class test implements functions{

public void getdata() {

System.out.println(x + " " +y);}}

class interfaceex {

public static void main(String args[]){

test ob1=new test();

ob1.getdata(); }}

Page 43: Inheritance and package.pdf

Program 5interface data {

int x=0;

double y=2.3;

void setdata(); }

interface functions extends data {

void getdata(); }

class test implements functions{

public void getdata() {

System.out.println(x + " " +y);}}

class interfaceex {

public static void main(String args[]){

test ob1=new test();

ob1.getdata(); }}//Error

Page 44: Inheritance and package.pdf

Figure 2

Student

Code

Name

test

Part 1

Part 2

Sports (Interface)

Sport weight=6

Results

Total

Page 45: Inheritance and package.pdf

PACKAGE

Page 46: Inheritance and package.pdf

Package

• Problem: Unique name had to be used for each class to avoid

name collisions.

• Java provides mechanism for partitioning class name space

into more manageable chunks. This mechanism is the package.

• We can define classes inside package that are not accessible by

code outside that package.

Page 47: Inheritance and package.pdf

Defining a Package

• Include package command in a java source file.

• Any classes declared within that file will belong to the

specified package.

• If we omit package statement, the class names are put into

default package, which has no name.

• But default package is inadequate for real applications.

• The general form of the package statement:

package pkg;

Here pkg is the name of the package.

Page 48: Inheritance and package.pdf

Example

• Package Firstpackage;

• Here, we have created Firstpackage.

• Java uses file system directories to store

packages. For example, the .class files for any

classes that you declared to be part of that

same Firstpackage must be stored in a

directory called Firstpackage. Means directory

name must match package name exaclty.

Page 49: Inheritance and package.pdf

Simple package package Firstpackage;

class balance{

String name;

double bal;

balance(String n, double b){

name=n;

bal=b;

}

void show(){

if(bal<0)

System.out.println(name +”:$ “ + bal);

}

}

class accountbalance{

public static void main(String args[]){

balance current[]=new balance[2];

current[0]=new balance(“Will Telll” , 157.02);

current[1]=new balance(“Tom Jackson”, 123.23);

For(int i=0;i<3;i++) current[i].show(); } }

Page 50: Inheritance and package.pdf

• save this file accountbalance.java and put in a

directory called Firstpackage.

• Compile the file.

– javac Firstpackage\accountbalance.java

• Execute by using following command line.

java Firstpackage.accountbalance

Page 51: Inheritance and package.pdf

Accessing Packages

• The general form of import statement for searching a class is

as follows:

– Import package1[.package2].classname;

• Here package1 is the name of the top level package, package2

is the name of the package that is inside the package1.

– Import packagename.*;

• Here, packagename may denote a single package or hierarchy

of packages. „*‟ implies that we can access all classes

contained in the above package directly.

Page 52: Inheritance and package.pdf

Access Protection

• Anything declared public may seen 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.

Page 53: Inheritance and package.pdf

Class Access Levels

• A class has only two possible access levels.

– Default.

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

Page 54: Inheritance and package.pdf

Example

package package1;

public class classA

{

public void displayA()

{

System.out.println(“class A”);

}

}

Save classA.java and save in directory package1.

Page 55: Inheritance and package.pdf

Example

import package1.classA;

class packageTest1

{

public static void main(String args[])

{

classA objA=new ClassA();

objA.displayA();

}

}

Save this file packageTest1 and compile file.

Page 56: Inheritance and package.pdf

Example

import package1.classA;

class packageTest1

{

public static void main(String args[])

{

classA objA=new ClassA();

objA.display A();

}

}

//O/P?

Page 57: Inheritance and package.pdf

Example

import package1.classA;

class packageTest1

{

public static void main(String args[])

{

classA objA=new ClassA();

obj1.display ();

}

}

//class A

Page 58: Inheritance and package.pdf

Example

package package2;

public class classB

{

protected int m=10;

public void displayB()

{

System.out.println(“class B”);

System.out.println(“m=“ + m);

}

}

Source file and compiled file of this package are located in the subdirectory

package2.

Page 59: Inheritance and package.pdf

import package1.classA;

import package2.*;

class packageTest2

{

public static void main(string args[])

{

classA obj1= new classA();

classB obj2= new classB();

obj1.displayA();

obj1.displayB();

}

}

Page 60: Inheritance and package.pdf

Program

• Package1

• Package2

class personName,code

Class admin

Experience()

Class salary

Name,code,experience,Pay()

Page 61: Inheritance and package.pdf

Questions

1) Given a package named EDU.Student, how

would you import a class named Test

contained in this package? Write one line

statement.

import EDU.Student.Test;

Page 62: Inheritance and package.pdf

Questions

2) Consider the following class definition:

class student

{

Abstract double result();

}

This code will not compile since a keyword is

missing in the first line. What is the keyword?

Ans: abstract

Page 63: Inheritance and package.pdf

Questions

3)Consider the following class file?

import java.awt.*;

import java.io.*;

package studentBase;

class Test

{

Void display()

{

System.out.println(“Results”);

}

}

Will it compile? YES or NO. Give reason, if No:

Ans: No, the package definition come first

Page 64: Inheritance and package.pdf

Questions

4)Given below are two files:

File Employee.java File Company.java

Will the file Company. java compile? YES or NO. Give reason, if No.

Ans: No, the field age should be public in Employee.java.

package purchase;

Public class Employee

{

Protected double age=35.00;

}

import purchase.Employee;

public class Company

{

Public static void main(String args[])

{

Employee e=new Employee();

System.out.println(“Age=“, + e.age);

}

}

Page 65: Inheritance and package.pdf

Questions

5) Consider the following class definition

class Student extends String

{

}

What happens when we try to compile this class?

A. Will not compile because class body is not defined

B. Will not compile because the class is not declared public

C. Will not compile because String abstract

D. Will not compile because String is final

E. Will compile successfully

Ans: D

Page 66: Inheritance and package.pdf

Questions6) Consider the following class definition

class Maths

{

Student student1;

}

class Student

{

String name;

}

This code represetns

A. An „is a‟ relationship

B. A „has a‟ relationship

C. Both

D. neither

Ans: B

Page 67: Inheritance and package.pdf

Questions7) Which of the following statements are true?

1. We cannot use abstract classes to instantiate objects directly.

2. The abstract methods of an abstract class must be defined in its subclass.

3. We cannot declare abstract constructors.

4. We may declare abstract static methods.

A. Line 1 only.

B. Line 2 only

C. Line 1 and line 2 only

D. Line 1, line 2 and line 3 only.

E. All are true.

Ans: D

Page 68: Inheritance and package.pdf

Questions8) Which keyword can protect a class in a package from accessibility by the

classes outside the package?

Ans: Dont use any keyword (make it default)

Page 69: Inheritance and package.pdf

Questions9) A package is a collection of

A. Classes

B. Interfaces

C. Classes and interfaces

D. None of the above

Ans: C

Page 70: Inheritance and package.pdf

Questions10) Package p1 contains the following code:

Package p1;

public class Student { Body of student class}

class Test { Body of Test class }

Now consider the following code:

import p1.*;

class Result

{ Student s1;

Test t1; }

This code will not compile because

A. Classes Result should be declared public.

B. Student class is not available.

C. Test class is not available.

D. Body of Result class is not fully defined.

Ans: C

Page 71: Inheritance and package.pdf

Questions11) Can an abstract method be declared final?

Ans: No

Page 72: Inheritance and package.pdf

Questions12) Can an abstract method be declared static?

Ans: No

Page 73: Inheritance and package.pdf

Questions13) Consider the following program

class Number

{

int x;

void store(Number num)

{

num.x++;

} }

class mainNumber

{

public static void main(String args[])

{

Number n= new Number();

n.x=10; n.store(10); System.out.println(n.x);

} }

Ans: 11

Page 74: Inheritance and package.pdf

Questions14) Consider the following program

class staticex

{

static int m=0;

static int n=0;

public static void main(String args[])

{

int m=10;

int x=20;

{

int n=30;

System.out.println("m+n=" + m+n);

}

x=m+n;

System.out.println("x=" + x); } }

Ans: m+n= 40

x=10

Page 75: Inheritance and package.pdf

Questions15) The concept of multiple inheritance is implemented in Java by

A. Extending two or more classes

B. Extending one class and implementing one or more interfaces

C. Implementing two or more interfaces

D. All the above.

Ans: B & C