0% found this document useful (0 votes)
13 views107 pages

JAVA-Variables,structure

Unit II covers inheritance, packages, and interfaces in Java, detailing types of inheritance such as single, multilevel, and hierarchical. It explains the concepts of superclass and subclass, the use of the 'super' keyword, and method overriding for achieving polymorphism. Additionally, it discusses the creation and access of packages and the differences between interfaces and abstract classes.

Uploaded by

thejegan31
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
13 views107 pages

JAVA-Variables,structure

Unit II covers inheritance, packages, and interfaces in Java, detailing types of inheritance such as single, multilevel, and hierarchical. It explains the concepts of superclass and subclass, the use of the 'super' keyword, and method overriding for achieving polymorphism. Additionally, it discusses the creation and access of packages and the differences between interfaces and abstract classes.

Uploaded by

thejegan31
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 107

UNIT II

 UNIT II- INHERITANCE, PACKAGES AND


INTERFACES
 Inheritance: Types of Inheritance-IS a relationship,has –a
Relationship - Super key word –final keyword,Polymorphism
–Method overloading and Method overriding - Abstract
classes
 Interfaces: Define –Extend – implement –Access –Interface vs
Abstract class, Type Conversion (Primitives to Object Vice
versa) Autoboxing and Auto unboxing
 Packages: Define, Create -Access - Import

1
Inheritance: Basic concepts
 Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object
Oriented programming system).
 The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class
also.
 Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.

2
 Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
 Terms used in Inheritance
 Class: A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
 Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the existing
class when you create a new class. You can use the same fields and
methods already defined in the previous class.

3
The syntax of Java Inheritance
 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.
 In the terminology of Java, a class which is
inherited is called a parent or superclass, and
the new class is called child or subclass.
4
Forms or Types of Inheritance
 On the basis of class, there can be three types of inheritance in java:
 Single
 multilevel
 hierarchical
 In java programming, multiple and hybrid inheritance is supported
through interface only.
 Single Inheritance:
 Single inheritance enables a derived class (sub class) to inherit properties
and behaviour from a single parent class (super class)
 Multilevel Inheritance :
 When a class is derived from a class which is also a derived from another
class (i.e) a class having more than one parent classes , such inheritance
is called multilevel inheritance .
 Hierarchical Inheritance:
 When more than one classes are derived from a single base class , such
inheritance is known as hierarchical inheritance.

5
Forms or Types of Inheritance

6
Inheritance – Single
 import java.io.*;
 import java.util.Scanner;
 class Student
 {
 public int regno;
 int year;
 String name;
 public void method()
 {
 Scanner ob = new Scanner(System.in);
 System.out.print("Enter student name:");
 name=ob.nextLine();
 System.out.print("Enter register number:");
 regno=ob.nextInt();
 System.out.print("Enter year:");
 year=ob.nextInt();
 }
 }
7
 class Marks extends Student
 {
 int arr[]=new int[5],tot;
 public void method2()
 {
 Scanner ob = new Scanner(System.in);
 System.out.print("Enter Student marks : ");
 for (int i=0;i<5;i++)
 {
 arr[i]=ob.nextInt();
 tot = tot + arr[i];
 }
 }
8
 public void display()
 {
 System.out.println("\t\t\t *****STUDENT DETAILS*****");
 System.out.println("Name :"+name);
 System.out.println("Register number:"+regno);
 System.out.println("Year:"+year);
 System.out.println("Total Marks Obtained :"+tot);
 }
 public static void main(String[] arg)
 {
 Marks s=new Marks();
 s.method();
 s.method2();
 s.display();
 }
 }
9
10
Inheritance – Hierarchical
 import java.io.*;
import java.util.Scanner;
 class Player
 {
 public int number;
 String name, role, country;
 public void method()
 {
 Scanner ob = new Scanner(System.in);
 System.out.print("Enter player name :");
 name=ob.nextLine();
 System.out.print("Enter Jersey number :");
 number=ob.nextInt();
 System.out.print("Enter the Nationality :");
 country=ob.nextLine();
 country=ob.nextLine();
 } }

11
 class Batsman extends Player
 { float avg;
 public void method1()
 {
 Scanner ob = new Scanner(System.in);
 System.out.print("Enter the Role of Batsman :"); role=ob.nextLine();
 System.out.print("Enter Batting Average:"); avg=ob.nextFloat();
 }
 public void display()
 {
 System.out.println("\n\t\t\t\t *Batsman Details*");
 System.out.println("Name : "+name);
 System.out.println("Jersey Number : "+number);
 System.out.println("Nationality : "+country);
 System.out.println("Specialist : "+role);
 System.out.println("Batting Average : "+avg);
 }
 }

12
 class Bowler extends Player
 {
 float avgb,eco;
 public void method2()
 {
 Scanner ob = new Scanner(System.in);
 System.out.print("Enter Bowling type : ");
 role=ob.nextLine();
 System.out.print("Enter Bowling average : ");
 avgb=ob.nextFloat();
 System.out.print("Enter Economy :");
 eco=ob.nextFloat();
 }

13
 public void display()
 {
 System.out.println("\n\t\t\t\t *Bowlwer Details*");
 System.out.println("Name : "+name);
 System.out.println("Jersey Number : "+number);
 System.out.println("Nationality : "+country);
 System.out.println("Specialist : "+role);
 System.out.println("Bowling Average : "+avgb);
 System.out.println("Economy : "+eco);
 }
 }

14
 class Heirarchical
 {
 public static void main(String[] arg)
 {
 Batsman ba=new Batsman();
 Bowler bo=new Bowler();
 System.out.println("Batsman Details ... ");
 ba.method();
 ba.method1();
 System.out.println("Bowler Details .... ");
 bo.method();
 bo.method2();
 System.out.println("\n\t\t\t *****PLAYER'S DETAILS*****");
 ba.display();
 bo.display();
 }
 }
15
16
Inheritance – Multilevel
 import java.util.*;
 class Grandparent
 {
 protected long aadharno;
 public String gpname;
 String address;
 String relegion;
 public void getgp()
 {
 Scanner s1=new Scanner(System.in);
 System.out.print("\nEnter the aadhar number:");
 aadharno=s1.nextLong();
 System.out.print("\nEnter the Grand Parent name:");
 gpname=s1.next();
 System.out.print("\nEnter the address:");
 address=s1.next();

 }
 }
17
 class Parent extends Grandparent
 {
 String pname,occ;
 public void getp()
 {
 Scanner s2=new Scanner(System.in);
 System.out.print("\nEnter the Parent name:");
 pname=s2.next();
 System.out.print("\nEnter the Occupation:");
 occ=s2.next();
 }
 }

18
 class Child extends Parent
 {
 String cname;
 int age;
 public void getc()
 {
 Scanner s3=new Scanner(System.in);
 System.out.print("\nEnter child name:");
 cname=s3.next();
 System.out.print("\nEnter the age:");
 age=s3.nextInt();
 }
19
 public void display()
 {
 System.out.println("GrandParent:"+gpname);
 System.out.println("Address:"+address);
 System.out.println("AAdhar
number:"+aadharno);
 System.out.println("Parent name:"+pname);
 System.out.println("Parent
occupation:"+occ);
 System.out.println("Child name:"+cname);
 System.out.println("Age:"+age);
 }
 }
20
 class multi
 {
 public static void main(String []arg)
 {
 System.out.println("*****MULTILEVEL INHERITANCE*****");
 Child c=new Child();
 c.getgp();
 c.getp();
 c.getc();
 c.display();
 }
 }
21
Important facts about inheritance in Java
 Default superclass: Except Object class, which has no superclass,
every class has one and only one direct superclass (single
inheritance). In the absence of any other explicit superclass, every
class is implicitly a subclass of the Object class.
 Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is
because Java does not support multiple inheritances with classes.
Although with interfaces, multiple inheritances are supported by
java.
 Inheriting Constructors: A subclass inherits all the members
(fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked
from the subclass.
 Private member inheritance: A subclass does not inherit the
private members of its parent class. However, if the superclass has
public or protected methods(like getters and setters) for accessing
its private fields, these can also be used by the subclass.
22
SUPER KEYWORD
 The super keyword in Java is a reference variable
which is used to refer immediate parent class object.
 Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
 Usage of Java super Keyword
 super can be used to refer immediate parent class
instance variable.
 super can be used to invoke immediate parent class
method.
 super() can be used to invoke immediate parent class
constructor.

23
 Note: super() is added in each class
constructor automatically by compiler if there
is no super() or this().

24
 1. Use of “super” with  {
variables:  System.out.println("Maximum
 This scenario occurs when a Speed: " + super.maxSpeed);
derived class and base class  }
has same data members. In  }
that case there is a possibility 
of ambiguity for the JVM.
 class Test
 Examples:
 {
 class Vehicle
 public static void
 {
main(String[] args)
 intmaxSpeed = 120;  {
 }  Car small = new Car();
 class Car extends Vehicle  small.display();
 {  }
 intmaxSpeed = 180;  }
 void display()
25
 2. Use of super with methods: class");
 This is used when we want to call parent  }
class method. So whenever a parent and 
child class have same named methods  voiddisplay()
then to resolve ambiguity we use  {
“super” keyword.
 message();
 Examples:
 Super.message();
 classPerson
 }
 {
 }
 voidmessage()

 {
 classTest
 System.out.println("This is person
class");
 {
 }
 publicstaticvoidmain(String args[])
 }
 {
 classStudent extendsPerson
 Student s = newStudent();
 {
 s.display();
 voidmessage()
 }
 {
 }

 System.out.println("This is student

26
 3. Use of super with  {
constructors:  Student()
 Super keyword can also be used to  {
access the parent class  super();
constructor. One more important  System.out.println("Student class
thing is that, ‘’super” can call both
Constructor");
parametric and default constructor.
 }
 Examples:
 }
 class Person

 {
 class Test
 Person()
 {
 {
 public static void main(String[]
 System.out.println("Person
args)
class Constructor");
 {
 }
 Student s = new Student();
 }

 }
 }
 class Student extends Person
27
METHOD OVERRIDING:
 Overriding is a feature that allows a subclass or child
class to provide a specific implementation of a method
that is already provided by one of its super-classes or
parent classes.
 When a method in a subclass has the same name,
same parameters or signature and same return type(or
sub-type) as a method in its super-class, then the
method in the subclass is said to override the method
in the super-class.

28
Example:
 classParent  }
 { 

 voidshow()  classMain
 {  {
 System.out.println("Parent's  publicstaticvoidmain(String[]
show()"); args)
 }  {
 }  Parent obj = newChild();
 classChild extendsParent  obj.show();
 {  }
 voidshow()  }
 {  Output:
 super.show();  Parent's show()
System.out.println("Child's  Child's show()
show()");
 29 }
 Rules for method overriding:
 Overriding and Access-Modifiers :
 The access modifier for an overriding method can allow more, but
not less, access than the overridden method.
 Example: a protected instance method in the super-class can be
made public, but not private, in the subclass.
 Final methods cannot be overridden
 Static methods cannot be overridden
 Private methods cannot be overridden
 The overriding method must have same return type :
 From Java 5.0 onwards it is possible to have different return type
for a overriding method in child class, but child’s return type
should be sub-type of parent’s return type.

30
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access
level. For example: If the superclass method is declared public then the overridding
method in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared
public or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
 Constructors cannot be overridden.
31
Abstract class in Java
 A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
 Before learning the Java abstract class, let's understand the abstraction in Java
first.
Abstraction in Java
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
 Abstraction lets you focus on what the object does instead of how it does it.
 Ways to achieve Abstraction
 There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)

32
Abstract class in Java
 A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods. It needs
to be extended and its method implemented. It cannot be
instantiated.
 Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to
change the body of the method.
 Example of abstract class
 abstract class A
 {
 }
33
Abstract Method in Java
 A method which is declared as abstract and does not have implementation is known
as an abstract method.
 Example of abstract method
 abstract void printStatus();//no method body and abstract
 Example of Abstract class that has an abstract method
 In this example, Bike is an abstract class that contains only one
abstract method run. Its 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();
 }
34
Understanding the real scenario of Abstract class
 In this example, Shape is the abstract class, and its
implementation is provided by the Rectangle and Circle
classes.
 Mostly, we don't know about the implementation class
(which is hidden to the end user), and an object of the
implementation class is provided by the factory
method.
 A factory method is a method that returns the
instance of the class. We will learn about the factory
method later.
 In this example, if you create the instance of Rectangle
class, draw() method of Rectangle class will be invoked.

35
 abstract class Shape{
 abstract void draw();
 }
 //In real scenario, implementation is provided by others i.e. unknown by end user
 class Rectangle extends Shape{
 void draw(){System.out.println("drawing rectangle");}
 }
 class Circle1 extends Shape{
 void draw(){System.out.println("drawing circle");}
 }
 //In real scenario, method is called by programmer or user
 class TestAbstraction1{
 public static void main(String args[]){
 Shape s=new Circle1();//
In a real scenario, object is provided through method, e.g., getShape() method
 s.draw();
 }
 }
36
Another example of Abstract class in java
 abstract class Bank{
 abstract int getRateOfInterest();
 }
 class SBI extends Bank{
 int getRateOfInterest(){return 7;}
 }
 class PNB extends Bank{
 int getRateOfInterest(){return 8;}
 }

37
 class TestBank{
 public static void main(String args[]){
 Bank b;
 b=new SBI();
 System.out.println("Rate of Interest is: "+b.getRateOfInt
erest()+" %");
 b=new PNB();
 System.out.println("Rate of Interest is: "+b.getRateOfInt
erest()+" %");
 }}
 Output:
 Rate of Interest is: 7 %
 Rate of Interest is: 8 %
38
Another real scenario of abstract class
 The abstract class can also be used to provide some
implementation of the interface. In such case, the end user
may not be forced to override all the methods of the
interface.
 interface A{
 void a();
 void b();
 void c();
 void d();
 }
 abstract class B implements A{
 public void c(){System.out.println("I am c");}
 }
39
 class M extends B{
 public void a(){System.out.println("I am a");}
 public void b(){System.out.println("I am b");}
 public void d(){System.out.println("I am d");}
 }
 class Test5{
 public static void main(String args[]){
 A a=new M();
 a.a();
 a.b();
 a.c();
 a.d();
 }}
 Output:I am a I am b I am c I am d
40
Dynamic method dispatch or Runtime
Polymorphism
 Polymorphism in Java is a concept by which we can
perform a single action in different ways. Polymorphism
is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms.
So polymorphism means many forms.
 There are two types of polymorphism in Java:
 compile-time polymorphism and
 runtime polymorphism.
 We can perform polymorphism in java by method
overloading and method overriding.
 If you overload a static method in Java, it is the
example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.

41
Static vs Dynamic binding
No Key Static Binding Dynamic Binding

1 Basic It is resolved at It is resolved at run


compile time time
2 Resolve static binding use Dynamic binding
mechanism type of the class and uses object to
fields resolve binding
3 Example Overloading is an Method overriding is
example of static the example of
binding Dynamic binding

4. Type of private, final and Virtual methods use


Methods static methods and dynamic binding
variables uses static
binding

42
Runtime Polymorphism in Java
 Runtime polymorphism or Dynamic Method Dispatch is a
process in which a call to an overridden method is resolved at
runtime rather than compile-time.
 In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the
reference variable.
 Let's first understand the upcasting before Runtime Polymorphism.
 Upcasting
 If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example:

43
 class A{ }
 class B extends A{ }
 A a=new B();//upcasting
 For upcasting, we can use the reference variable of class type or an
interface type. For Example:
 interface I{ }
 class A{ }
 class B extends A implements I{ }
 Here, the relationship of B class would be:
 B IS-A A
 B IS-A I
 B IS-A Object
 Since Object is the root class of all classes in Java, so we can write B
IS-A Object.

44
Java Runtime Polymorphism Example: Bank
 Consider a scenario where Bank is a class that provides
a method to get the rate of interest. However, the rate
of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%,
and 9.7% rate of interest.

45
 class Bank{
 float getRateOfInterest(){return 0;}
 }
 class SBI extends Bank{
 float getRateOfInterest(){return 8.4f;}
 }
 class ICICI extends Bank{
 float getRateOfInterest(){return 7.3f;}
 }
 class AXIS extends Bank{
 float getRateOfInterest(){return 9.7f;}
 }
46
 class TestPolymorphism
 {
 public static void main(String args[]){
 Bank b;
 b=new SBI();
 System.out.println("SBI Rate of Interest: "+b.getRateOfInterest(
));
 b=new ICICI();
 System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()
);
 b=new AXIS();
 System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()
);
 }
 }
47
Advantages of Dynamic Method
Dispatch
 Dynamic method dispatch allow Java to support
overriding of methods which is central for run-time
polymorphism.
 It allows a class to specify methods that will be
common to all of its derivatives, while allowing
subclasses to define the specific implementation of
some or all of those methods.
 It also allow subclasses to add its specific methods
subclasses to define the specific implementation of
some.

48
Object class in Java
 The Object class is the parent class of all the classes
in java by default. In other words, it is the topmost
class of java.
 The Object class is beneficial if you want to refer any
object whose type you don't know. Notice that parent
class reference variable can refer the child class object,
know as upcasting.
 Let's take an example, there is getObject() method that
returns an object but it can be of any type like
Employee,Student etc, we can use Object class
reference to refer that object. For example:
 Object obj=getObject();

//we don't know what object will be returned from this me


thod
49

Methods of Object class
 The Object class provides many methods.
They are as follows:
Method Description
public final Class getClass() returns the Class class object of this
object. The Class class can further be
used to get the metadata of this class.
public int hashCode() returns the hashcode number for this
object.
public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy
CloneNotSupportedException (clone) of this object.
public String toString() returns the string representation of this
object.
public final void notify() wakes up single thread, waiting on this
object's monitor.

50
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the
InterruptedException specified milliseconds, until another thread
notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the
nanos)throws InterruptedException specified milliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until
InterruptedException another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before
object is being garbage collected.

51
PACKAGES
java package
 A java package is a group of similar types of classes,
interfaces and sub-packages.
 Package in java can be categorized in two form, built-in
package and user-defined package.
 There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
 Here, we will have the detailed learning of creating and
using user-defined packages.
 Advantage of Java Package
 1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
 2) Java package provides access protection.
 3) Java package removes naming collision.
53
54
Simple example of java package
 The package keyword is used to create a
package in java.
 //save as Simple.java
 package mypack;
 public class Simple{
 public static void main(String args[]){
 System.out.println("Welcome to package");
 }
 }

55
 How to compile java package
 If you are not using any IDE, you need to follow the syntax given below:
 javac -d directory javafilename
 For example
 javac -d . Simple.java
 The -d switch specifies the destination where to put the generated class
file. You can use any directory name like /home (in case of Linux), d:/abc
(in case of windows) etc. If you want to keep the package within the
same directory, you can use . (dot).
 How to run java package program
 You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
 To Compile: javac -d . Simple.java
 To Run: java mypack.SimpleOutput:Welcome to package
 The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.

56
How to access package from another
package?
 There are three ways to access the package
from outside the package.
 import package.*;
 import package.classname;
 fully qualified name.

57
1) Using packagename.*
 If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
 The import keyword is used to make the classes and interface of another package
accessible to the current package.
 Example of package that import the packagename.*
 //save by A.java
 package pack;
 public class A{
 public void msg(){System.out.println("Hello");}
 }
 //save by B.java
 package mypack;
 import pack.*;
 class B{
 public static void main(String args[]){
 A obj = new A();
 obj.msg();
 }
 }
58
2) Using packagename.classname
 If you import package.classname then only declared class of this package will
be accessible.
 Example of package by import package.classname
 //save by A.java
 package pack;
 public class A{
 public void msg(){System.out.println("Hello");}
 }
 //save by B.java
 package mypack;
 import pack.A;

 class B{
 public static void main(String args[]){
 A obj = new A();
 obj.msg();
 }
 }
59
3) Using fully qualified name
 If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util
and java.sql packages contain Date class.
 Example of package by import fully qualified name
 //save by A.java
 package pack;
 public class A{
 public void msg(){System.out.println("Hello");}
 }
 //save by B.java
 package mypack;
 class B{
 public static void main(String args[]){
 pack.A obj = new pack.A();//using fully qualified name
 obj.msg();
 } }
60
 Note: If you import a package, subpackages will not be imported.
 If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces of
the subpackages. Hence, you need to import the subpackage as
well.
 Note: Sequence of the program must be package then import
then class.

61
Subpackage in java
 Package inside the package is called the subpackage.
It should be created to categorize the package
further.
 Let's take an example, Sun Microsystem has definded a
package named java that contains many classes like
System, String, Reader, Writer, Socket etc.
 These classes represent a particular group e.g. Reader
and Writer classes are for Input/Output operation,
Socket and ServerSocket classes are for networking etc
and so on.
 So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
62
 Example of Subpackage
 package com.javatpoint.core;
 class Simple{
 public static void main(String args[]){
 System.out.println("Hello subpackage");
 }
 }
 To Compile: javac -d . Simple.java
 To Run: java com.javatpoint.core.Simple

63
 How to send the class file to another directory or drive?
 There is a scenario, I want to put the class file of A.java source file in
classes folder of c: drive. For example:
 //save as Simple.java
 package mypack;
 public class Simple{
 public static void main(String args[]){
 System.out.println("Welcome to package");
 }
 }
 To Compile:
 e:\sources> javac -d c:\classes Simple.java
 To Run:
 To run this program from e:\source directory, you need to set classpath of
the directory where the class file resides.e:\sources> set classpath=c:\
classes;.;e:\sources> java mypack.Simple

64
 Another way to run this program by -classpath switch of java:
 The -classpath switch can be used with javac and java tool.
 To run this program from e:\source directory, you can use -classpath
switch of java that tells where to look for class file. For example:
 e:\sources> java -classpath c:\classes mypack.Simple
 Ways to load the class files or jar files
 There are two ways to load the class files temporary and permanent.
 Temporary
 By setting the classpath in the command prompt
 By -classpath switch
 Permanent
 By setting the classpath in the environment variables
 By creating the jar file, that contains all the class files, and copying the jar
file in the jre/lib/ext folder.

65
Example
 package pack;
 import java.io.*;
 public class Compute
 {
 int a,b;
 public void add(int a,int b)
 {
 System.out.println("The result of addition is :" +(a+b));
 }
 public void sub(int a,int b)
 {
 System.out.println("The result of subtraction is :" +(a-b));
 }

66
 public void mul(int a,int b)
 {
 System.out.println("The result of
multiplication is :" +(a*b));
 }
 public void div(int a,int b)
 {
 System.out.println("The result of
division is :" +(a/b));
 }
 }
67
 import pack.Compute;
 import java.io.*;
 import java.util.Scanner;
 class Calculate
 {
 public static void main(String args[])
 {
 int a,b,ch;
 Scanner s1=new Scanner(System.in);
 System.out.println("Enter two numnber : ");
 System.out.print(" A : ");
 a=s1.nextInt();
 System.out.print(" B : ");
 b=s1.nextInt();
 System.out.println("Enter the operation to be performed : ");
 System.out.println(" 1. Addition \n 2. Subtraction" );

68
 System.out.println(" 3. Multiplication \n 4. Division ");
 System.out.print("Enter the choice :");
 ch=s1.nextInt();
 Compute c=new Compute();
 switch(ch)
 {
 case 1: c.add(a,b);
 break;
 case 2: c.sub(a,b);
 break;
 case 3: c.mul(a,b);
 break;
 case 4: c.div(a,b);
 break;
 default: System.out.println("Invalid choice...");
 }
 }
 }

69
70
INTERFACE
Interface in Java
 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.
 In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
 Java Interface also represents the IS-A relationship.
 It cannot be instantiated just like the abstract class.
 Since Java 8, we can have default and static methods in
an interface.
 Since Java 9, we can have private methods in an
interface.
72
Why use Java interface?
 There are mainly three reasons to use interface. They
are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of
multiple inheritance.
 It can be used to achieve loose coupling.

73
Difference between class and Interface
An interface is different from a class in several ways,
including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only
fields that can appear in an interface must be declared
both static and final.
 An interface is not extended by a class; it is
implemented by a class.
 An interface can extend multiple interfaces.
Defining Interface
 The Java compiler adds public and abstract
keywords before the interface method.
Moreover, it adds public, static and final
keywords before data members.

79
Implementing Interface
Interface variable
Extending interface
Example
 interface ISports
 {
 public void SetTeam(String t1,String t2, int score1, int score2);
 public void ShowResult();
 }

 class Cricket implements ISports
 {
 String team1,team2;
 int team1Runs,team2Runs;
 public void SetTeam(String t1,String t2, int r1, int r2)
 {
 team1 = t1;
 team2 = t2;
 team1Runs = r1;
 team2Runs = r2;
 }


 public void ShowResult()
 {
 System.out.println("\t\t\t*Cricket*");
 System.out.println("\t" +team1 + " - " + team1Runs + " Runs");
 System.out.println("\t" +team2 + " - " + team2Runs + " Runs");
 if(team1Runs>team2Runs)
 {
 System.out.println("\t"+team1+" Won");
 }
 else
 {
 System.out.println("\t"+team2+" Won");
 }
 }
 }

101
 class Hockey implements ISports
 {
 String team1,team2;
 int team1Goals,team2Goals;
 public void SetTeam(String t1,String t2, int r1,
int r2)
 {
 team1 = t1;
 team2 = t2;
 team1Goals = r1;
 team2Goals = r2;
 }
102
 public void ShowResult()
 {
 System.out.println("\t\t\t*Hockey*");
 System.out.println("\t"+team1 + " - " + team1Goals + " Goals");
 System.out.println("\t"+team2 + " - " + team2Goals + " Goals");
 if(team1Goals>team2Goals)
 {
 System.out.println("\t"+team1 + " Won");
 }
 else
 {
 System.out.println("\t"+team2 + " Won");
 }
 }
 }

103
 class Sports
 {
 public static void main(String args[])
 {
 Cricket c = new Cricket();
 Hockey h = new Hockey();

 c.SetTeam("India", "England",240,220);
 h.SetTeam("India", "Germany",3,2);

 c.ShowResult();
 h.ShowResult();

 }
 }
104
Output

105
End of II Unit

107

You might also like