KEMBAR78
Oops Unit II | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
6 views36 pages

Oops Unit II

Unit II of the IT T45 Java Programming course covers inheritance, packages, and interfaces, focusing on method overloading, passing and returning objects, nested and inner classes, and types of inheritance. It includes detailed explanations and examples of concepts such as method overloading, object passing, nested classes, and various inheritance types like single, multilevel, and hierarchical inheritance. Additionally, it discusses method overriding and its advantages in Java programming.

Uploaded by

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

Oops Unit II

Unit II of the IT T45 Java Programming course covers inheritance, packages, and interfaces, focusing on method overloading, passing and returning objects, nested and inner classes, and types of inheritance. It includes detailed explanations and examples of concepts such as method overloading, object passing, nested classes, and various inheritance types like single, multilevel, and hierarchical inheritance. Additionally, it discusses method overriding and its advantages in Java programming.

Uploaded by

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

IT T45 JAVA PROGRAMMING – UNIT II

UNIT II
INHERITANCE, PACKAGES AND INTERFACES : Overloading Methods – Objects as
Parameters – Returning Objects – Static - Nested and Inner Classes - Inheritance - Basics –
Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –
Abstract Classes – final with Inheritance - Packages and Interfaces - Pack ages – Packages and
Member Access – Importing Packages – Interfaces.

1. Explain Method Overloading with example program.


Method overloading results when two or more methods in the same class have the same
name but different parameters.
Methods with the same name must differ in their types or number of parameters. This
allows the compiler to match parameters and choose the correct method when a number of
choices exist. Changing just the return type is not enough to overload a method, and will be a
compile-time error. They must have a different signature.
When no method matching the input parameters is found, the compiler attempts to
convert the input parameters to types of greater precision. A match may then be found without
error. At compile time, the right implementation is chosen based on the signature of the method
call.
Example

public class MethodOverloadDemo


{
void sumOfParams() { // First Version
System.out.println("No parameters");
}
void sumOfParams(int a) { // Second Version
System.out.println("One parameter: " + a);
}
int sumOfParams(int a, int b) { // Third Version
System.out.println("Two parameters: " + a + " , " + b);
return a + b;
}
double sumOfParams(double a, double b) { // Fourth Version
System.out.println("Two double parameters: " + a + " , " + b);
return a + b;
}
IT/MVIT/IV SEM Page 1
IT T45 JAVA PROGRAMMING – UNIT II

public static void main(String args[]) {


MethodOverloadDemo moDemo = new MethodOverloadDemo();
int intResult;
double doubleResult;
moDemo.sumOfParams();
System.out.println();
moDemo.sumOfParams(2);
System.out.println();
intResult = moDemo.sumOfParams(10, 20);
System.out.println("Sum is " + intResult);
System.out.println();
doubleResult = moDemo.sumOfParams(1.1, 2.2);
System.out.println("Sum is " + doubleResult);
System.out.println();
}
}
Output:-
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

2.Explain about Passing and Returning Objects in Java?

The passing and returning of objects between methods is a basic feature of Java programming
and is essential to creating reliable, modular programs. In this section, we will discuss passing
and returning objects in Java, exploring different kinds and methods along the way and
offering complete code examples for a comprehensive understanding.

Passing Objects in Java:

In Java, passing objects involves more than just data transfer; it also involves managing the flow
of references to these objects. It presents a distinct set of considerations because Java adheres to
the reference passing paradigm. Objects involve passing the value of their reference rather than
the actual object, in contrast to primitive data types where values are supplied directly.

IT/MVIT/IV SEM Page 2


IT T45 JAVA PROGRAMMING – UNIT II

Method Parameters:

Java's handling of object references in method parameters adds a layer of complexity to object
passing. Understanding that Java transfers references by value is crucial. This means that instead
of the actual object, only the reference to it is transferred. Let's delve into a basic illustration to
clarify this concept:

Example :

class Person {
String name;
Person(String name) {
this.name = name;
}
}
public class ObjectPassingExample {
public static void modifyPersonName(Person person) {
person.name = "Ram Kumar";
}
public static void main(String[] args) {
Person person = new Person("Ravi");
System.out.println("Before modification: " + person.name);
modifyPersonName(person);
System.out.println("After modification: " + person.name);
}
}

OUTPUT:

Before modification: Ravi


After modification: Ram Kumar

Returning Objects:

Methods in Java can return objects, allowing for flexible and reusable code. Here's an example:

Example:

class Calculator {
IT/MVIT/IV SEM Page 3
IT T45 JAVA PROGRAMMING – UNIT II

int result;
Calculator(int initialValue) {
this.result = initialValue;
}
public Calculator add(int value) {
this.result += value;
return this;
}
public Calculator subtract(int value) {
this.result -= value;
return this;
}
}
public class ObjectReturningExample
{
public static void main(String[] args) {
Calculator calculator = new Calculator(10);
int finalResult = calculator.add(5).subtract(3).result;
System.out.println("Final result: " + finalResult);
}
}

OUTPUT:
Final result: 12

4. Explain in detail about Nested Classes and inner Classes.


Nested Classes
The Java programming language allows you to define a class within another class. Such a
class is called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
class OuterClass {
...

IT/MVIT/IV SEM Page 4


IT T45 JAVA PROGRAMMING – UNIT II

static class StaticNestedClass {


...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes)
have access to other members of the enclosing class, even if they are declared private. Static
nested classes do not have access to other members of the enclosing class. As a member of
the OuterClass, a nested class can be declared private, public, protected, or package private.
(Recall that outer classes can only be declared public or package private.)

Why Use Nested Classes?


Compelling reasons for using nested classes include the following:
 It is a way of logically grouping classes that are only used in one place: If a class is
useful to only one other class, then it is logical to embed it in that class and keep the two
together. Nesting such "helper classes" makes their package more streamlined.
 It increases encapsulation: Consider two top-level classes, A and B, where B needs
access to members of A that would otherwise be declared private. By hiding class B
within class A, A's members can be declared private and B can access them. In addition,
B itself can be hidden from the outside world.
 It can lead to more readable and maintainable code: Nesting small classes within top-
level classes places the code closer to where it is used.

Static Nested Classes


As with class methods and variables, a static nested class is associated with its outer
class. And like static class methods, a static nested class cannot refer directly to instance
variables or methods defined in its enclosing class: it can use them only through an object
reference.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

INNER CLASSES:
Inner classes, also called Nested Classes, are nothing but classes that are defined within
other classes.
Java inner classes have feature that makes them richer and more useful. An object of an
inner class has an implicit reference to the outer class object that instantiated it. Through this
pointer, it gains access to any variable of the outer object. Only static inner classes don’t have
this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner
classes are actually a phenomenon of the compiler and not the JVM.

IT/MVIT/IV SEM Page 5


IT T45 JAVA PROGRAMMING – UNIT II

Inner classes may be defined with following access modifiers : public, protected, private,
or with default package access.

The syntax for inner class is as follows:

[modifiers] class OuterClassName {


code...
[modifiers] class InnerClassName {
code....
}
}
Static Inner Classes:
Syntax for static inner class is as follows:

<access-specifier> class OuterClassName {


public static class <StaticInnerClassName> {
. . .}
. . .}
For static inner classes following additional properties hold:
 Static members of the outer class are visible to the static inner class, what ever their
access level be.
 Non-static members of the outer class are not available, because there is not instance of
the outer class.
 An inner class may not have static members unless the inner class is itself marked
as static.
 Sometimes static nested class are not refered to as inner class at all, as they don’t require
outer classes instance.
 A static inner class is just like any other inner class, but it dose not have the reference to
its outer class object that generated it.

Local Inner Classes:


Syntax of the local inner class is as follows:
<access-specifier> class <OuterClassName> {
code...
<access-specifier> <return-type> <MethodName>(<arguments>){
class <LocalInnerClassName>{
code...}
code...}
code...}
 Local classes are never declared with an access specifier (that is, public or private). Their
scope is always restricted to the block in which they are declared.
 Local classes have a great advantage: they are completely hidden from the outside world.

IT/MVIT/IV SEM Page 6


IT T45 JAVA PROGRAMMING – UNIT II

 They can not only access the instance variables but local variables of the method (in
which they are defined) as well, but the local variable has to be declared final.

5. Explain about inheritance and types in java with examples?


The mechanism of deriving a new class from an old class is called as inheritance. The old
class is known as the base class or super class or parent class and the new class is called the
subclass or derived class or child class. Inheritance may take different sub forms as follows,
 Single inheritance
 Multiple inheritances
 Hierarchical inheritance
 Multilevel inheritance

Syntax:-
class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is a parent class of B
and B would be a child class of A.
import java.io.*;
class Player
{
String pname;
Player(String name1)
{
pname=name1;
}
void display()
{
System.out.println("Player Name:"+pname);
}
}
class Cricket extends Player
{
String pos;
Cricket(String name, String pos1)
IT/MVIT/IV SEM Page 7
IT T45 JAVA PROGRAMMING – UNIT II

{
super(name);
pos=pos1;
}
void output()
{
System.out.println("Cricket Player Details");
display();
System.out.println("Position:"+pos);
}
}
class Single
{
public static void main(String arg[])
{
Cricket c1=new Cricket("Sachin", "First");
Cricket c2=new Cricket("Dravid", "Fourth");
c1.output();
c2.output();
}
}

Multiple Inheritances
Java does not support the concept of multiple inheritances however this concept is
implemented using a secondary interface path in the form of interfaces. An interface in a class is
defined using implements.

Multilevel Inheritance
For this the common requirement is the use of the derived class as a super class . Here
the class A serves as a base class for the derived class B which in turn serves as the base class for
the derived class C. the chain ABC is known as inheritance path.
Class A
{
}
Class B extends A
{
}
IT/MVIT/IV SEM Page 8
IT T45 JAVA PROGRAMMING – UNIT II

Class C extends B
{
}

class Car
{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car
{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
IT/MVIT/IV SEM Page 9
IT T45 JAVA PROGRAMMING – UNIT II

public class Multilevel extends Maruti


{
public Multilevel()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
Super.speed();
}
public static void main(String args[])
{
Multilevel obj=new Multilevel();
obj.vehicleType();
obj.brand();
obj.speed();
}
}

Hierarchial Inheritance
Using hierarchical inheritance many programming problems can be cast into a hierarchy
where certain features of one level are shared by many others below the level. This inheritance is
used as a support to the hierarchical design of a program.
Eg: hierarchical classification of accounts in a commercial bank
class Birds
{
public void fly()
{
System.out.println(“Generally,Birds fly”);
}
}
class Parrot extends Birds
{

IT/MVIT/IV SEM Page 10


IT T45 JAVA PROGRAMMING – UNIT II

public void eat()


{
System.out.println("Parrot eats fruits and seeds");
}
}
class Vulture extends Birds
{
public void vision()
{
System.out.println("Vulture can see from high altitudes");
}
}
public class Hierarchial
{
public static void main(String args[])
{
Parrot p1=new Parrot();
p1.eat();
p1.fly();
Vulture v1=new Vulture();
v1.vision();
v1.fly();
}
}

4. Explain about Method Overriding in detail.


Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as Method Overriding.

IT/MVIT/IV SEM Page 11


IT T45 JAVA PROGRAMMING – UNIT II

Advantage of Java Method Overriding


 Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method Overriding is used for Runtime Polymorphism

Rules for Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method is same
and there is IS-A relationship between the classes, so there is method overriding.
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
Output:
Bike is running safely

Real example of Java Method Overriding

IT/MVIT/IV SEM Page 12


IT T45 JAVA PROGRAMMING – UNIT II

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But,
rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7% and 9% rate of interest.

class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
IT/MVIT/IV SEM Page 13
IT T45 JAVA PROGRAMMING – UNIT II

}
}

class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

5. Explain about Abstract class in detail.


Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.

Abstract class in Java


A class that is declared with abstract keyword is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).
It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class


abstract class A
{
}

abstract method

IT/MVIT/IV SEM Page 14


IT T45 JAVA PROGRAMMING – UNIT II

A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method


abstract void printStatus(); //no body and abstract

Example of abstract class that has abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output:-
running safely..

Another example of abstract class in java


abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}

IT/MVIT/IV SEM Page 15


IT T45 JAVA PROGRAMMING – UNIT II

class PNB extends Bank


{
int getRateOfInterest()
{
return 8;
}
}

class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Output:-
Rate of Interest is: 7 %
Rate of Interest is: 8 %

6. Explain about Dynamic Method Dispatch.

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 related to a principle that states that an super class
reference can store the reference of subclass object.
However, it can't call any of the newly added methods by the subclass but a call to an
overridden methods results in calling a method of that object whose reference is stored in the
super class reference.
It simply means that which method would be executed, simply depends on the object
reference stored in super class object.
When Parent class reference variable refers to Child class object, it is known
as Upcasting.

IT/MVIT/IV SEM Page 16


IT T45 JAVA PROGRAMMING – UNIT II

Example for Dynamic Method Dispatch


class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme() // override callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
void callme() // override callme()
{
System.out.println("Inside C's callme method");
}
}

public class Dynamic_disp


{
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

IT/MVIT/IV SEM Page 17


IT T45 JAVA PROGRAMMING – UNIT II

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

Output:-
Inside A's callme method
Inside B's callme method
Inside C's callme method

7. Discuss about using final with Inheritance.


final is a keyword in java used for restricting some functionalities. We can declare
variables, methods and classes with final keyword.

The keyword final has three uses


1. It can be used to create the equivalent of a named constant
2. Using final to prevent overriding
3. Using final to prevent inheritance

1. Using final to Prevent Overriding


While method overriding is one of Java’s most powerful features. 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.

Example1:using final to Prevent Overriding


class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
IT/MVIT/IV SEM Page 18
IT T45 JAVA PROGRAMMING – UNIT II

Here meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a


compile-time error will result.

2. Using final 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. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
class B extends A // ERROR! Can't subclass A
{
// ...
}

8. Explain about package and types in java?


Packages are Java’s way of grouping a variety of classes and/or interfaces together. The
grouping is usually done according to functionality.
We have repeatedly stated that one of the main features of OOP is its ability to reuse the
code already created.
1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two
classes in two different packages can have same name. They may be refer by their fully
qualified name, comprising the package name and the class name.
3. Packages provide a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”.

TYPES OF PACKAGES:
Packages are of two types. They are:
 Java API Packages
 User Defined Package

JAVA API PACKAGE:

IT/MVIT/IV SEM Page 19


IT T45 JAVA PROGRAMMING – UNIT II

 Java.langLanguage support classes. These are classes that Java compiler itself uses and
therefore itself uses and therefore they are automatically imported. They include classes
for primitive types, strings, math functions, threads and exceptions.
 Java.utilLanguage utility classes such as vectors, hash tables, random numbers, date
etc..
 Java.ioInput/Output support classes. They provide facilities for the input and output of
data.
 Java.awtSet of packages for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
 Java.netClasses for networking. They include classes for communicating with local
computers as well as with internet servers.
 Java.appletClasses for creating and implementing applets.

Java API

lang util io awt net applet

USER DEFINED PACKAGE:


User defined package is created by user. The user defined package is of two types. They are:
 Creating a package
 Accessing a package

CREATING A PACKAGE:
Java system packages are organized and used. creating our own packages is by:
We must first declare the name of the packages using the package keyword followed by a
package name. This must be the first statement in a Java source file. Then we define a class, just
as we normally define a class. Here is an example:
Package first Package; // package declaration
Public class First-Class // class definition
IT/MVIT/IV SEM Page 20
IT T45 JAVA PROGRAMMING – UNIT II

{
……………….
……………….
………………
}

ACCESSING A PACKAGE:
A Java system package can be accessed either using a fully quantifies class name or using
a shortcut approach through the import statement. We can use the import statement when there
are many references to a particular package name are too long and unwidely.

The general form of import statement for searching a class is as follows:


import package1 [.package2] [.package3].classname;

Example Program of a Package:


Package addsub;
public class addition
{
public void add(int a,int b)
{
int c=a+b;
System.out.println(c);
}
}
public class subtraction
{
public void sub(int a,int b)
{
int c=a-b;
System.out.println(c);
}
}
Package muldiv;
public class multiplication
{
public void mul(int a,int b)
{
int c=a*b;
System.out.println( c );
}
IT/MVIT/IV SEM Page 21
IT T45 JAVA PROGRAMMING – UNIT II

}
public class division
{
public void div(int a,int b)
{
int c=a/b;
System.out.println( c );
}
}

import addsub.*;
import muldiv.*;
class TestPackage
{
public static void main(String arg[])
{
addition a=new addition();
a.add(10,20);
subtraction s=new subtraction();
s.sub(20,45);
multiplication m=new multiplication();
m.mul(5,6);
division d=new division();
d.div(2,5);
}
}
Output:-
30
-25
30
0

9. Discuss about Classpath and importing of Packages.


CLASSPATH Variable
 CLASSPATH - environment variable that points to the root directory of the system’s
package hierarchy.
 Several root directories may be specified in CLASSPATH,
 e.g. the current directory and the C:\raju\myJava directory:
.;C:\raju\myJava
Java will search for the required packages by looking up subsequent directories described in the
CLASSPATH variable.
IT/MVIT/IV SEM Page 22
IT T45 JAVA PROGRAMMING – UNIT II

Finding Packages
 Consider this package statement:
package myPackage;
 In order for a program to find myPackage, one of the following must be true:
1) program is executed from the directory immediately above myPackage (the
parent of myPackage directory)
2) CLASSPATH must be set to include the path to myPackage

Example: Package
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);
}
}

Example: Main
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++)
{
current[i].show();
}
}
}

IT/MVIT/IV SEM Page 23


IT T45 JAVA PROGRAMMING – UNIT II

Output:-
K. J. Fielding: $123.23
Will Tell: $157.02
-->> Tom Jackson: $-12.33

 Save, compile and execute:


1) call the file AccountBalance.java
2) save the file in the directory MyPack
3) compile; AccountBalance.class should be also in MyPack
4) set access to MyPack in CLASSPATH variable, or make the parent of MyPack
your current directory
5) run: java MyPack.AccountBalance

Make sure to use the package-qualified class name.

Importing of Packages
 Since classes within packages must be fully-qualified with their package names, it would
be tedious to always type long dot-separated names.
 The import statement allows to use classes or whole packages directly.
 Importing of a concrete class:
import myPackage1.myPackage2.myClass;
 Importing of all classes within a package:
import myPackage1.myPackage2.*;
 Import Statement
The import statement occurs immediately after the package statement and before
the class statement:
package myPackage;
 import otherPackage1;otherPackage2.otherClass;
class myClass { … }
 The Java system accepts this import statement by default:
import java.lang.*;
 This package includes the basic language functions. Without such functions, Java is of no
much use.

Example: Packages 1
A package MyPack with one public class Balance.
The class has two same-package variables: public constructor and a public show method.

package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
IT/MVIT/IV SEM Page 24
IT T45 JAVA PROGRAMMING – UNIT II

name = n;
bal = b;
}
public void show()
{
if (bal<0)
{
System.out.print("-->> ");
}
System.out.println(name + ": $" + bal);
}
}

Example: Main
The importing code has access to the public class Balance of the MyPack package and its
two public members:

import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show();
}
}

Java Source File


 Finally, a Java source file consists of:
1) a single package instruction (optional)
2) several import statements (optional)
3) a single public class declaration (required)
4) several classes private to the package (optional)
 At the minimum, a file contains a single public class declaration.
10. Explain about interface in java with examples?
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Interface Definition
visibility mode interface interfaceName
{
constant variable declarations
IT/MVIT/IV SEM Page 25
IT T45 JAVA PROGRAMMING – UNIT II

abstract method declarations


}

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface:

Example:
import java.lang.*;
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:


 An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.
Example:

/* File name : Animal.java */


interface Animal
{
public void eat();
public void travel();
}

Implementing Interfaces:
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal
{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");

IT/MVIT/IV SEM Page 26


IT T45 JAVA PROGRAMMING – UNIT II

}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}}
This would produce following result:
Mammal eats
Mammal travels

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend
another class. The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
Another Example:-
interface Maths1
{
void add();
}
interface Maths2
{
void sub();
}
interface Maths3

IT/MVIT/IV SEM Page 27


IT T45 JAVA PROGRAMMING – UNIT II

{
void mul();
}

class Addition implements Maths1


{
public void add() {
int a=6,b=4;
int sum=a+b;
System.out.println(sum);
}
}
class Subtraction implements Maths2
{
public void sub() {
int a=6,b=4;
int diff=a-b;
System.out.println(diff);
}
}
class Multiplication implements Maths3
{
public void mul() {
int a=6,b=4;
int multiply=a*b;
System.out.println(multiply);
}
}

public class InterfaceExample


{
public static void main(String[]args)
{
Addition a=new Addition();
a.add();
Subtraction s=new Subtraction();
s.sub();
Multiplication m=new Multiplication();
m.mul();
IT/MVIT/IV SEM Page 28
IT T45 JAVA PROGRAMMING – UNIT II

}
}

As shown in the above diagram, a class extends another class, an interface extends another
interface but a class implements an interface.

Interface inheritance
A class implements interface but one interface extends another interface .

interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{

IT/MVIT/IV SEM Page 29


IT T45 JAVA PROGRAMMING – UNIT II

TestInterface4 obj = new TestInterface4();


obj.print();
obj.show();
}
}

Output:

Hello
Welcome

11. Difference between classes and interfaces


Class : A Java class is a virtual construct in Programming world, which can be
instantiated to create Logical object to represent a Physical entity in the Virtual / Programming
environment.
Every Object instantiated from a Class will have a state, and a behavior. These objects
will communicate with other Objects in their virtual world using this behavior.
We will take a deep dive about this communication between the objects in a short while.

Syntax
modifier class myClass
{ //class header
//field, constructor
//method declarations
};

Class Definition:
public class Vehicle
{ // syntax of class
int steering; // these are the instance variables
int wheels;
Vehicle(int wheelCpunt)
{ // Is a constructor of the class
wheels = wheelCount;
}
int getWheels()
{
return wheels;
}
}

In the above code snippet, public is a modifier and class keyword specifies that the
Vehicle is a type of Class, and the second and third lines are having two variables, these are
IT/MVIT/IV SEM Page 30
IT T45 JAVA PROGRAMMING – UNIT II

called instance variables and they hold the state of an object when instantiated. The fifth line
contains a Constructor for the class which will be called when an object is instantiated for the
vehicle, and sets the state of the object by giving them the passed values or default values.
In the above snippet when an Object of Vehicle is created, the state of wheels field is set
by the parameter to the constructor, and the steering is given a default value which is 0 for an
int.

Interface :
A Java Interface is also a virtual construct in programming world, but in contrary to the
Java Class, Interface cannot be instantiated or created as an object. An Interface denotes a group
of logical entities.
It can also act as a contract between two sub systems, while communicating with each
other.

public interface Vehicle


{ // syntax of class
int steeringCount = 2;
int getWheels();
}

class MyClass extends MySuperClass implements YourInterface


{
// field, constructor, and
// method declarations
}

The above code snippet, defines an interface called Vehicle. An interface will not have a
constructor and cannot be instantiated or an object cannot be created for this type. The variables
in an Interface are called Class variables / Static variables, since they cannot have instances they
should be able to communicate using the Class Name itself. In addition to being a static variables
these are also final by default which makes them not to be altered by any other objects.

Some of the differences between a class and an Interface

Property Class Interface

Instantiation Can Be Instantiated Cannot be instantiated

State Each Object created will have its Each objected created after
own state implementing will have the same state

IT/MVIT/IV SEM Page 31


IT T45 JAVA PROGRAMMING – UNIT II

Behavior Every Object will have the same Every Object will have to define its
behavior unless overridden. own behavior by implementing the
contract defined.

Inheritance A Class can inherit only one An Interface cannot inherit any classes
Class and can implement many while it can extend many interfaces
interfaces

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

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

12. Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there will
be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.

Consider the example,

class A
{
void msg()
{
System.out.println("Hello");
}
}

IT/MVIT/IV SEM Page 32


IT T45 JAVA PROGRAMMING – UNIT II

class B
{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String args[])
{
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}

Multiple inheritance is not supported through class in java but it is possible only by
interface.

Syntax:-
interface if1{}
interface if2{}
class MyClass implements if1,if2
{
// field, constructor, and
// method declarations
}

Example:-

IT/MVIT/IV SEM Page 33


IT T45 JAVA PROGRAMMING – UNIT II

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Multiple implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
Multiple obj = new Multiple();
obj.print();
obj.show();
}
}

Output:
Hello
Welcome

13. Write a Java program to maintain the books details like BookId, accession number;
book name, author, publication in books packages and keep the journal details such as
journal Id; journal name; in journal package in main class use these two packages details
for staff and student classes and display the books and journals information as requested
by the user.

package books;
class Book
{

IT/MVIT/IV SEM Page 34


IT T45 JAVA PROGRAMMING – UNIT II

int bookid;
String bookname;
String author;
String publication;
Book(int bid, String bname, String author, String publication)
{
this.bookid = bid;
this.bookname=bname;
this.author= author;
this.publication= publication;
}
Book getBooks()
{
return this;
}
}

package journals;
class Journal
{
int journalid;
String journalname;
Journal(int jid, String jname)
{
this.journalid=jid;
this.journalname=jname;
}
Journal getJournal()
{
return this;
}

import journal.*;
import books.*;
class Staff
{
Staff()
{
IT/MVIT/IV SEM Page 35
IT T45 JAVA PROGRAMMING – UNIT II

Journal j=new Journal(121, "IEEE");


j.getJournal();
System.out.println(j.journalid);
System.out.println(j.journalname);
}
}

class Student
{
Student()
{
Book b = new Book(111, "JAVA PROGRAMMING", "HARI",
"PEARSON");
b.getBooks();
System.out.println(b.bookid);
System.out.println(b.bookname);
System.out.println(b.author);
System.out.println(b.publication);
}
}

class Access
{
public static void main(String args[])
{
Staff s= new Staff();
Student s1=new Student();
}
}

IT/MVIT/IV SEM Page 36

You might also like