Вы находитесь на странице: 1из 75

Inheritance

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

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

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();//?
}
}

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

Constructor called
class A{
A(){
}
}
Class B extends A{
B(){
}
}
class mainconst{
public static void main(String args[ ]){
B ob=new B();
}
}

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.

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

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

Illustration of super
public class Inheritance {
public static void main(String[] args) {
derived d=new derived(11,22);
d.show1();
}
}

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

A second use for super


class example{
Public static void main(String args[])
{
second subobj =new second(1,2);
Subobj.show();
}
}

Creating Multilevel Hierarchy


person
Name,code

admin
Experience

salary
Name,code,exp
erience,Pay()

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.

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

class override{
public static void main(string args[]){
B subob=new B(1,2,3);
subob.show();
}
}
Output:
K:3

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

Output:
i and j:1 2
K:3

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

class override{
public static void main(string args[]){
B subob=new B(1,2,3);
subob.show();
}
}

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

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.

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

Using Final With Inheritance


Using final to prevent overriding
Class a{
final void math1(){
-----}
}
Class b extends a{
Void meth1()//Error
{
----}
}

Using Final With Inheritance


Using final to prevent inheritance
final class a{
}
Class b extends a{ //error
}

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.

Staff
Code
Name

teacher
Subject
publication

typist

Officer

Speed

grade

Figure 1

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

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 Curracct and Sav-acct to make them more specific to their
requirements include the necessary methods in order to
achieve the following tasks:

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 .

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

Interfaces
interface name{
Return_type methodname1(parameter list);
Return_type methodname2(parameter_list);

Type variable name1=value;


Type variable name2=value;
.
}

Method are declared inside interface.


Variables are final and static.

Implementing interface
class classname [extends superclass]
[implements interfacename1, interfacename2]

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?
}
}

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

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?
}
}

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

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

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

Program 4
interface 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

Program 5
interface 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(); }}

Program 5
interface 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

Student
Code
Name

test

Sports (Interface)

Part 1
Part 2

Sport weight=6

Results
Total

Figure 2

PACKAGE

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.

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.

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.

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

save this file accountbalance.java


directory called Firstpackage.
Compile the file.

and put in a

javac Firstpackage\accountbalance.java

Execute by using following command line.


java Firstpackage.accountbalance

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.

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.

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.

Example
package package1;
public class classA
{
public void displayA()
{
System.out.println(class A);
}
}
Save classA.java and save in directory package1.

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.

Example
import package1.classA;
class packageTest1
{
public static void main(String args[])
{
classA objA=new ClassA();
objA.display A();
}
}
//O/P?

Example
import package1.classA;
class packageTest1
{
public static void main(String args[])
{
classA objA=new ClassA();
obj1.display ();
}
}
//class A

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.

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

Program
Package1

Package2

class person
Name,code

Class admin
Experience()

Class salary

Name,code,exp
erience,Pay()

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;

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

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

Questions
4)Given below are two files:
File Employee.java
package purchase;
Public class Employee
{
Protected double age=35.00;
}

File Company.java
import purchase.Employee;
public class Company
{
Public static void main(String args[])
{
Employee e=new Employee();
System.out.println(Age=, + e.age);
}
}

Will the file Company. java compile? YES or NO. Give reason, if No.
Ans: No, the field age should be public in Employee.java.

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

Questions
6) 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

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

Questions
8) 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)

Questions
9) A package is a collection of
A. Classes
B. Interfaces
C. Classes and interfaces
D. None of the above
Ans: C

Questions
10) 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

Questions
11) Can an abstract method be declared final?

Ans: No

Questions
12) Can an abstract method be declared static?

Ans: No

Questions
13) 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

Questions
14) 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

Questions
15) 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

Вам также может понравиться