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

Unit II Java

Uploaded by

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

Unit II Java

Uploaded by

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

IT T45- Java Programming

Unit: II
Basic concepts, member access rules, usage of super key word, forms of inheritance, method overriding, abstract classes,
dynamic method dispatch, using final with inheritance, the Object class. Defining, Creating and Accessing a Package,
Understanding CLASSPATH, importing packages, differences between classes and interfaces, defining an interface,
implementing interface, applying interfaces, variables in interface and extending interfaces.

2.1 Basic concepts, member access rules- Java Access Modifiers

In java we have four access modifiers:


1. default
2. private
3. protected
4. public

2.1.1. Default access modifier


When we do not mention any access modifier, it is called default access modifier. The scope of
this modifier is limited to the package only. This means that if we have a class with the default access
modifier in a package, only those classes that are in this package can access this class. No other class
outside this package can access this class. Similarly, if we have a default method or data member in a
class, it would not be visible in the class of another package.

Default Access Modifier Example in Java

In this example we have two classes, Test class is trying to access the default method of Addition class,
since class Test belongs to a different package, this program would throw compilation error, because
the scope of default modifier is limited to the same package in which it is declared.
Addition.java

package abcpackage;

public class Addition {


/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java

package xyzpackage;

/* We are importing the abcpackage


* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test {

SMVEC-Department of Information Technology Page 1


IT T45- Java Programming

public static void main(String args[]){


Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)

2. Private access modifier


The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from outside of
the class.

Private access modifier example in java


This example throws compilation error because we are trying to access the private data member
and method of class ABC in the class Example. The private data member and method are only
accessible within the class.
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:

Compile - time error

3. Protected Access Modifier


Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is similar to
default access modifier with one exception that it has visibility in sub classes.

SMVEC-Department of Information Technology Page 2


IT T45- Java Programming

Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.
Example:

In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class extends class
Addition and the protected modifier allows the access of protected members in subclasses (in any
packages).
Addition.java

package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}
Test.java

package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:

33
4. Public access modifier
The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.

Example:
The method addTwoNumbers() has public modifier and class Test is able to access this method without
even extending the Addition class. This is because public modifier has visibility everywhere.
Addition.java
package abcpackage;

public class Addition {

public int addTwoNumbers(int a, int b){


return a+b;
}
}

SMVEC-Department of Information Technology Page 3


IT T45- Java Programming

Test.java
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:

101
The scope of access modifiers in tabular form

2.2 Super Keyword in java:


The super keyword in java is a reference variable that is used to refer parent class objects. It
always refers to the object of the immediate parent class.
When the object is created for sub class , an instance (object) of parent class is called implicitly, which
can be referenced by super class variable.

Usage of Super keyword:


 Used to refer immediate parent class instance variable
 Used to invoke the immediate parent class method
 Used to invoke the immediate super class constructor.

2.2.1. Use of super with variables: This is used when a derived class and base class has same data
members. In that case there is a possibility of ambiguity for the JVM.
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;

SMVEC-Department of Information Technology Page 4


IT T45- Java Programming

void display()
{

System.out.println("Maximum Speed: " + maxSpeed);


System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
MaximumSpeed:180
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could access
maxSpeed of base class in sublcass using super keyword.
2.2.2. Use of super with methods:
This is used when we want to call parent class method. So whenever a parent and child class have same
named methods then to resolve ambiguity we use super keyword.
class Person
{
void message()
{
System.out.println("This is person class");
}
}

class Student extends Person


{
void message()
{
System.out.println("This is student class");
}
void display()
{
// will invoke or call current class message( ) method
message();

// will invoke or call parent class message( ) method


super.message( );
}
}
SMVEC-Department of Information Technology Page 5
IT T45- Java Programming

class Test
{
public static void main(String args[])
{
Student s = new Student();

// calling display( ) of Student


s.display();
}
}

Output:
This is student class
This is person class

In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be invoked.
2.2.3. Use of super with constructors:
 The super keyword can also be used to access the parent class constructor.
 The’super’ can call both parametric as well as non parametric constructors depending upon the
situation.
 The call to super( ) must be the first statement in derived class constructor.
 If a subclass constructor invokes a constructor of its super class , either explicitly or implicitly ,
they are called in chain method.
class Person
{
Person( )
{
System.out.println("Person class Constructor");
}
}

class Student extends Person


{
Student()
{
// invoke or call parent class constructor
super( );

System.out.println("Student class Constructor");


}
}

SMVEC-Department of Information Technology Page 6


IT T45- Java Programming

class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:

Person class Constructor

Student class Constructor

2.3 Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another class.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Need of Inheritance:
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o 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. The subclass can add its own fields and methods
in addition to the super class fields and methods.
o Super Class/Parent Class: Super class is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
o 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.

Syntax of Java Inheritance


class Superclass-name
{
}
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.

SMVEC-Department of Information Technology Page 7


IT T45- Java Programming

2.3.1 Types of Inheritance in Java (or) Forms of Inheritance in java


 Single Inheritance
 Multiple Inheritance (Through Interface)
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance (Through Interface)

2.3.1.1 Single Inheritance : In single inheritance, subclasses inherit the features of one superclass.

import java.io.*;
import java.util.Scanner;

class Student
{

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

SMVEC-Department of Information Technology Page 8


IT T45- Java Programming

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

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

2.3.1.2 Multilevel Inheritance :

In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, the class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.

SMVEC-Department of Information Technology Page 9


IT T45- Java Programming

import java.io.*;
import java.util.Scanner;

class Student
{

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

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

SMVEC-Department of Information Technology Page 10


IT T45- Java Programming

class Extra extends Marks


{
double attend;
String sports,languages;

public void method3( )


{
Scanner ob = new Scanner(System.in);
System.out.print("Enter attendance Percentage:");
attend=ob.nexDouble();
System.out.print("Enter Sports Interested:");
sports=ob.next();
System.out.print("Enter the language Interested:");
languages=ob.next();
}
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);
System.out.println("Attendance:"+attend);
System.out.println("Sports:"+sports);
System.out.println("Language:"+languages)

}
class Helper
{
public static void main(String[] arg)
{
Extra s=new Extra();
s.method();
s.method2();
s.method3( );
s.display();
}
}

2.3.1.3 Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class. The class A serves as a base class for the derived class B,C and D.

SMVEC-Department of Information Technology Page 11


IT T45- Java Programming

import java.util.*;
class Student
{
String name,dob,mailid;
long phno;
void getdata()
{
Scanner inp=new Scanner(System.in);
System.out.println("Enter the name:");
name=inp.next();
System.out.println("Enter the Date of Birth:");
dob=inp.next();
System.out.println("Enter the mail id:");
mailid=inp.next();
}
}
class UGadmission extends Student
{
float m1,m2;
String schname;
void get()
{
Scanner inp=new Scanner(System.in);
System.out.println("Enter the 12th mark:");
m1=inp.nextFloat();
System.out.println("Enter the CGPA:");
cgpa=inp.nextFloat();
System.out.println("Enter the college name:");
collegename=inp.next();
}
void display()
{
System.out.println("Name:"+name);
System.out.println("Date of Birth:"+dob);
System.out.println("Phone no:"+phno);
System.out.println("Mail id:"+mailid);
SMVEC-Department of Information Technology Page 12
IT T45- Java Programming

System.out.println("12th mark:"+m1);
System.out.println("CGPA:"+cgpa);
System.out.println("College name:"+collegename);
}
}
class Hierarchicalinheritance
{
public static void main(String[]args)
{
UGadmission ob1=new UGadmission();
ob1.getdata();
ob1.get();
ob1.display();
PGadmission ob2=new PGadmission();
ob2.getdata();
ob2.get();
ob2.display();
}
}

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

 There must be is-a relationship between the 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.
 It achieves run time polymorphism.

Run time polymorphism:
The version of a method that is executed will be determined by the object that is used to invoke
it. If an object of a parent class is used to invoke the method, then the version in the parent class will be
executed, but if an object of the subclass is used to invoke the method, then the version in the child
class will be executed. It is defines as it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed

Rules for method overriding:


 Protected instance method in superclass can be made public in sub class ,but not as private in
sub class
 The final methods cannot be overridden
 The static methods cannot be overridden, because static methods are bound to certain class.
 We cannot override constructor as parent and child class can never have constructor with same
name

SMVEC-Department of Information Technology Page 13


IT T45- Java Programming

 The overriding method must have same return type (or subtype)

Method Hiding:
It is defined as defining a static method with the same signature as in base class in the derived
class is known as method hiding.
Example for Method Overriding:
class Shape
{
void draw()
{
System.out.println(“Drawing basic shapes”);
}
}
class Circle extends Shape
{
void draw()
{
int r=5;
System.out.println(“Drawing a circle”);
int area= r*r;
System.out.println(“Area of circle”+area);

}
}
class Rectangle extends Shape
{
void draw()
{
int len=10,b=20;
System.out.println(“Drawing aRectangle”);
int area= len*b;
System.out.println(“Area of Rectangle”+area);

}
}
class Helper
{
public static void main(String[]args)
{
Shape s = new Shape();
s.draw();
Circle c= new Circle();
c.draw();
Rectangle r = new Rectangle();
r.draw();
}
}

SMVEC-Department of Information Technology Page 14


IT T45- Java Programming

2.5 Abstract classes

Abstraction: It is the way of hiding the implementation and showing only the functionality to
the user. There are two ways to achieve abstraction:

 Abstract class
 Interfaces

Abstract Class: A class which is declared with the abstract keyword is known as abstract class
in java. The abstract class can have

 Abstract Methods
 Concrete methods - Non abstract methods

Rules for java abstract class:

 Abstract class must be declared with abstract keyword


 It can have abstract and non-abstract methods.
 It can be used as base class to extend and implement the abstract method
 No objects can be created for the abstract class. i.e it cannot be instantiated
 it can have constructors and static methods
 It can have final methods.
 The sub class derived from the abstract class must either implement all the abstract methods.
abstract class Employee
{
abstract int getsalary( );
void details()
{
String dept=”Development”;
String company=”TCS”;
}
}
class Developer extends Employee
{
int getsalary( )
{
int sal=40000;
return sal;
}
}
class TeamLeader extends Employee
{
int getsalary( )
{
int sal=80000;
return sal;
}
}

SMVEC-Department of Information Technology Page 15


IT T45- Java Programming

class Test
{
public static void main(String[]args)
{
Developer d = new Developer( );
d.details( );
d.getsalary( );

TeamLeader t = new TeamLeader( );


t.details( );
t.salary( );
}
}

2.6 Dynamic Method Dispatch

Runtime Polymorphism in Java is achieved by Method overriding in which a child class


overrides a method in its parent. An overridden method is essentially hidden in the parent class, and is
not invoked unless the child class uses the super keyword within the overriding method. This method
call resolution happens at runtime and is termed as Dynamic method dispatch mechanism.

 When an overridden method is called through a superclass reference, Java determines which
version (superclass/subclasses) of that method is to be executed based upon the type of the object
being referred to at the time the call occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This is also known as upcasting.
Java uses this fact to resolve calls to overridden methods at run time.

class Bank
{
void interest( )
{
System.out.println(“ Interest rate calculation”);
}
}

SMVEC-Department of Information Technology Page 16


IT T45- Java Programming

class ABC extends Bank


{
void interest( )
{
System.out.println(“ Interest rate for ABC Bank 8%”);
}
}
class XYZ extends Bank
{
void interest( )
{
System.out.println(“ Interest rate for XYZ Bank 10%”);
}
}
class Test
{
public static void main(String[]args)
{
Bank ob=new bank( );
ob.interest( );

Bank ob2=new ABC ( );


ob2.interest( );

Bank ob3=new XYZ ( );


ob3.interest( );

}
}

Output:
Interest rate calculation
Interest rate for ABC Bank 8%
Interest rate for XYZ Bank 10%

2.7 Using final with Inheritance in Java


The final is a keyword in java used for restricting some functionality. We can declare variables,
methods and classes with final keyword. In inheritance it can be used for two purposes:
 Final method in inheritance
 Final class in Inheritance

2.7.1 Final method in inheritance:


 The Final method can be inherited but cannot be overridden
 During inheritance, we must declare methods with final keyword for which we required to follow
the same implementation throughout all the derived classes.

SMVEC-Department of Information Technology Page 17


IT T45- Java Programming

 Note: It is not necessary to declare final methods in the initial stage of inheritance(base class
always). We can declare final method in any subclass for which we want that if any other class
extends this subclass, then it must follow same implementation of the method as in the that
subclass.
Example:

class XYZ
{
final void demo( )
{
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ


{
void demo()
{
System.out.println("ABC Class Method");
}
}
class Helper
{

public static void main(String args[])


{

ABC obj= new ABC();


obj.demo();
}
}
Output:
Compilation error

The above program would throw a compilation error, however we can use the parent class final method
in sub class without any issues. This program would run fine as we are not overriding the final method.
That shows that final methods are inherited but they are not eligible for overriding.

2.7.2 Final class in inheritance


It prevents from inheritance . A class is likely to be used by other programmers, to prevent
inheritance if any subclass created would cause problem.
The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted by a
subclass.
final class Bike{ }

class Honda1 extends Bike

SMVEC-Department of Information Technology Page 18


IT T45- Java Programming

void run()

System.out.println("running safely with 100kmph");

public static void main(String args[])

Honda1 honda= new Honda();

honda.run();

2.8 Object class In Java

 Object class is present in java.lang package.


 Every class in Java is directly or indirectly derived from the Object class.
 If a Class does not extend any other class then it is direct child class of Object and if extends
other class then it is an indirectly derived.
 Therefore the Object class methods are available to all Java classes.
 Hence Object class acts as a root of inheritance hierarchy in any Java Program.

Constructor of Object:
Object ( )

SMVEC-Department of Information Technology Page 19


IT T45- Java Programming

2.8.1 Methods in Object Class:

toString() : It provides String representation of an Object and used to convert an object to String.

hashCode( ) For every object, JVM generates a unique number which is hash code. It returns distinct
integers for distinct objects. Returns a hash value that is used to search object in a collection.
JVM(Java Virtual Machine) uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc. The main advantage of saving objects based on hash
code is that searching becomes easy.

equals(Object obj) : Compares the given object to “this” object (the object on which the method is
called).

getClass() : Returns the class object of “this” object and used to get actual runtime class of the object.

Example:
public class Test
{
public static void main(String[] args)
{
Object obj = new String("Hello");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "+ c.getName());
}
}
Output:
Class of Object obj is : java.lang.String

finalize() method : This method is called just before an object is garbage collected. It is called by
the Garbage Collector on an object when garbage collector determines that there are no more references
to the object.

clone() : It returns a new object that is exactly the same as this object. For clone() method refer Clone()

wait(), notify() notifyAll() are related to Concurrency. wait ( )- causes the current thread to wait for the
specified milliseconds and nanoseconds, notify( )-until another thread notifies wakes up single thread,
waiting on this object's monitor .notifyall ( )- wakes up all the threads, waiting on this object's monitor.

2.9 Packages in Java


Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).

SMVEC-Department of Information Technology Page 20


IT T45- Java Programming

Java language supports two types of packages. They are

 Built in Packages (or) Java API packages


 User Defined Packages

2.9.1 Java API Packages:

Java language has a rich set of built in API packages from which we can access interfaces and classes,
and then fields, constructors, and methods.

Java API Packages

Package Description

java.lang Package that contains essential Java classes, including numerics,


strings, objects, compiler, runtime, security, and threads.

java.io Package that provides classes to manage input and output


streams to read data from and write data to files, strings, and
other sources.

java.util Package that contains miscellaneous utility classes, including


generic data structures, bit sets, time, date, string manipulation,
random number generation, system properties, notification, and
enumeration of data structures.

java.net Package that provides classes for network support, including


URLs, TCP sockets, UDP sockets, IP addresses, and a binary-to-
text converter.

SMVEC-Department of Information Technology Page 21


IT T45- Java Programming

java.awt Package that provides an integrated set of classes to manage user


interface components such as windows, dialog boxes, buttons,
checkboxes, lists, menus, scrollbars, and text fields. (AWT =
Abstract Window Toolkit)

java.awt.image Package that provides classes for managing image data,


including color models, cropping, color filtering, setting pixel
values, and grabbing snapshots.

java.applet Package that enables the creation of applets through the Applet
class. It also provides several interfaces that connect an applet to
. its document and to resources for playing audio

2.9.2 Using Java API Packages:

The Java Package name consists of words separated by periods. The first part of the name
contains the name java. The remaining words of the Java Package name reflect the contents of the
package. The Java Package name also reflects its directory structure. For example the statement

java.awt

represents the awt (Abstract Window Toolkit) package.


To import a class from the package into our program you have to use the import statement. The syntax
is
import packagename.classname
or
import packagename.*;
Naming Conventions:

 Packages can be named using the standard java naming rules.


 Packages begin with lower case letters to distinguish package name from class name.
 Class name begins with upper case letters

This statement uses a fully qualified name Math to invoke the method sqrt( ).The methods begin with
lower case letters

SMVEC-Department of Information Technology Page 22


IT T45- Java Programming

Example for Predefined package

import java.util.Date;

public class DateDemo {

public static void main(String args[]) {

// Instantiate a Date object

Date date = new Date();

// display time and date using toString()

System.out.println(date.toString());

This will produce the following result −

Output
on Mar 04 09:51:52 CDT 2018

2.9.3 User Defined Packages

 We can create our own package and use it in our programs. Creation of package in java is easy.
 We must first declare the name of the package using the package keyword followed by a
package name. This must be the first statement in a Java source file (except for comments and
white spaces).
Steps involved in creation of Package:

The various steps involved in creation of package are listed below.

1. Declare the name of the package with package keyword. This must be the first statement in Java
source file.
package packagename;

SMVEC-Department of Information Technology Page 23


IT T45- Java Programming

2. The second step is to define classes and interfaces and put it inside the package. A package can
contain any number of classes; however one of the classes should have the public access specifier.
For example
package mypack
public class sample
{
//body of the class
}
3. Import the package in the other class by
import packagename.classname;
4. Compile the package program
>javac Calculate.java

5. Create a directory to place the class file


>javac –d . Calculate.java
Which create a folder with the class file of the package in the current working directory

>javac -d .. Calculate.java
Which creates a folder with the class file of the package in the root directory

Example :

Creating a Package:

package mypack;
public class Calculate
{
public void add(int a,int b)
{
System.out.println("Addition:"+(a+b));
}
public void sub(int a,int b)
{
System.out.println("Subtraction:"+(a-b));
}
}

SMVEC-Department of Information Technology Page 24


IT T45- Java Programming

Importing the package:

import mypack.Calculate;
import java.util.*;
class Compute
{
public static void main(String[]args)
{
int a,b;
Scanner inp=new Scanner(System.in);
System.out.println("Enter 2 input values:");
a=inp.nextInt();
b=inp.nextInt();
Calculate ob=new Calculate();
ob.add(a,b);
ob.sub(a,b);
}
}

Output:
>javac Calculate.java

>javac -d . Calculate.java

>javac Compute.java

>java Compute

2.10 CLASSPATH in Java:

It is actually an environment variable in Java and tells the Java applications and JVM where to find the
libraries of classes.These included both the predefined and user defined packages(libraries)

2.10.1 Environment variable:

It is a global system variable accessible by the computer operating ,other variables that are in
the environment variable are : computer name and user name.

In Java CLASSPATH holds the list of Java class file directories and the JAR(Java Archive files)which
is delivered class library file.

2.10.2 When to change the CLASSPATH:

When a standalone Java program is trying to run, we have to change the class path variable
when the program start executes the Java’s runtime system is called.

SMVEC-Department of Information Technology Page 25


IT T45- Java Programming

Interpreter runs through the code , if it reads the class name, it will look at each directory listed
in the CLASSPATH variable, if it does not find the class name it displays error.

c:\> set CLASSPATH=c:\Java\CustomClasses\lib

c:\> set CLASSPATH= c:\Java\CustomClasses\classes.zip

2.10.3 -classpath command:

Specifying the class path when running programs in JDK.

c:\>java -classpath c:\java\customclasses\Example.java

2.10.4 How classes are the found:

Bootstrap classes: It includes the rt.jar(runtime) and other classes.

Extension classes: classes bundled as JAR files snd kept in the $JAVA_HOME/jre/lib/ext

User classes: The class is located via -classpath or -cp command line option or CLASSPATH
environment variables

2.10.5 Difference between Path and CLASSPATH:


Path CLASSPATH

It is an environment variable which is used to It is an environment variable used by System or


locate JDK binaries java and javac Application Class Loader to locate and load the
compiled java byte code stored in . class file
Set path have to include jdk\bin directory Set CLASSPATH include all those directories
where we have placed our .class file
The path cannot be overridden The CLASSPATH can be overridden by providing
–classpath or –cp
It is the variable used by OS to find any binary It is used by Java Class Loader to load class files

2.11 Interfaces :

2.11.1 Why multiple inheritances are not supported in java?

To reduce the complexity and simplify the language, multiple inheritances are 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 the same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.

Interface : An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

SMVEC-Department of Information Technology Page 26


IT T45- Java Programming

Syntax :

interface <interface_name>

// declare constant fields

// declare methods that abstract

// by default.

To declare an interface, use interface keyword. It is used to provide total abstraction. That means all
the methods in interface are declared with empty body and are public and all fields are public, static and
final by default. A class that implement interface must implement all the methods declared in the
interface. To implement interface use implements keyword.

2.11.2 Need of Interface

 It is used to achieve total abstraction.


 Since java does not support multiple inheritance in case of class, but by using interface it can
achieve multiple inheritance.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use interfaces when we
have abstract classes?
 The reason is, abstract classes may contain non-final variables, whereas variables in interface
are final, public and static.

// A simple interface
interface Player
{
final int id = 10;
int move()
}

2.11.3 Interface variables:

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value
of the variable must be assigned in a static context in which no instance exists. The final modifier
ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by
program code.

SMVEC-Department of Information Technology Page 27


IT T45- Java Programming

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

public interface Iteam


{
void setteam(String team1,String team2);
}
public interface Iscore
{
void setscore(int s1,int s2);
}
class Details implements Iteam,Iscore
{
int s1,s2;
String t1,t2;
public void setteam(String x1,String x2)
{
t1=x1;
t2=x2;
System.out.println("Team 1:"+t1);
System.out.println("Team 2:"+t2);
}
public void setscore(int sc1,int sc2)
{
s1=sc1;
s2=sc2;
System.out.println("Score 1:"+s1);
System.out.println("Score 2:"+s2);
}
}
class Interfaceexample
{
public static void main(String[]args)
{
Details ob=new Details();
ob.setteam("India","Australia");
ob.setscore(245,200);
}
}

SMVEC-Department of Information Technology Page 28


IT T45- Java Programming

2.11.5 Extending Interfaces


An interface can extend another interface in the same 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.

The following Sports interface is extended by Hockey and Football interfaces.

Example

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

// Filename: Hockey.java

public interface Hockey extends Sports {

public void homeGoalScored();

public void visitingGoalScored();

public void endOfPeriod(int period);

public void overtimePeriod(int ot);

SMVEC-Department of Information Technology Page 29


IT T45- Java Programming

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to
define the three methods from Football and the two methods from Sports.

2.11.6 Difference between Class and Interfaces:

BASIS FOR
CLASS INTERFACE
COMPARISON

Basic A class is instantiated to An interface can never be instantiated as


create objects. Object can the methods are unable to perform any
be created action on invoking. The object cannot be
created

Keyword class interface

Access specifier The members of a class can The members of an interface are always
be private, public or public.
protected.

Methods The methods of a class are The methods in an interface are purely
defined to perform a abstract.
specific action.

Implement/Extend A class can implement any An interface can extend multiple


number of interfaces and interfaces but cannot implement any
can extend only one class. interface.

Constructor A class can have An interface can never have a constructor


constructors to initialize the as there is hardly any variable to
variables. initialize.

Variables It can be of any type The variables are final ,static

SMVEC-Department of Information Technology Page 30


IT T45- Java Programming

Two Marks
1. List out the various Java Access Modifiers (or) access specifiers

In java we have four access modifiers:


1. default
2. private
3. protected
4. public

2. Write short notes on Super Keyword in java.


The super keyword in java is a reference variable that is used to refer parent class objects.
It always refers to the object of the immediate parent class.
When the object is created for sub class , an instance (object) of parent class is called
implicitly, which can be referenced by super class variable.

3. What are the different Usage of Super keyword?


 Used to refer immediate parent class instance variable
 Used to invoke the immediate parent class method
 Used to invoke the immediate super class constructor.
4. Define Inheritance in Java. What is the need of inheritance?

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another class. Inheritance represents the IS-A relationship which
is also known as a parent-child relationship.

Need of Inheritance:
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
5. List the various Types of Inheritance in Java (or) Forms of Inheritance in java
 Single Inheritance
 Multiple Inheritance (Through Interface)
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance (Through Interface)

6. Define Method Overriding (or) How run time polymorphism is achieved in Java

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. It achieves
run time polymorphism.

7. What are the rules for method overriding?

 Protected instance method in superclass can be made public in sub class ,but not as private in
sub class
 The final methods cannot be overridden

SMVEC-Department of Information Technology Page 31


IT T45- Java Programming

 The static methods cannot be overridden, because static methods are bound to certain class.
 We can not override constructor as parent and child class can never have constructor with same
name
 The overriding method must have same return type (or subtype)

8. What is the difference between method overriding and method overloading

Method Overloading Method Overriding

Method overloading is used to increase Method overriding is used to provide the specific
the readability of the program. implementation of the method that is already
provided by its super class.

Method overloading is performed within Method overriding occurs in two classes that have
class. IS-A (inheritance) relationship.

In case of method overloading, parameter In case of method overriding, parameter must be


must be different. same.

Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

9. Define Abstract classes


A class which is declared with the abstract keyword is known as abstract class in java.
 It can be used as base class to extend and implement the abstract method
 No objects can be created for the abstract class. i.e it cannot be instantiated
The abstract class can have
 Abstract Methods
 Concrete methods - Non abstract methods

10. List the Rules for java abstract class?

 Abstract class must be declared with abstract keyword


 It can have abstract and non-abstract methods.
 It can be used as base class to extend and implement the abstract method

SMVEC-Department of Information Technology Page 32


IT T45- Java Programming

 No objects can be created for the abstract class. i.e it cannot be instantiated
 it can have constructors and static methods
 It can have final methods.
 The sub class derived from the abstract class must either implement all the abstract methods.

11. What is the need of using final with Inheritance in Java


The final is a keyword in java used for restricting some functionalities. We can declare
variables, methods and classes with final keyword. In inheritance it can be used for two purposes:
 Final method in inheritance- method can be inherited but cannot be overridden
 Final class in Inheritance- prevents from class to be inherited.

12. Define the term package in java?


Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Java language supports two types of packages. They are
• Built in Packages (or) Java API packages
• User Defined Packages
13. Why multiple inheritances are 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 the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

14. Does Java supports multiple Inheritance?Justify


No, Java does not supports multiple inheritance in java, instead it uses interfaces where it
contains abstract methods.

15. Difference between Class and Interfaces?

BASIS FOR
CLASS INTERFACE
COMPARISON

Basic A class is instantiated to An interface can never be instantiated as


create objects. Object can the methods are unable to perform any
be created action on invoking. The object cannot be
created

Keyword class interface

Access specifier The members of a class can The members of an interface are always
be private, public or public.
protected.

Methods The methods of a class are The methods in an interface are purely
defined to perform a abstract.
specific action.

SMVEC-Department of Information Technology Page 33


IT T45- Java Programming

BASIS FOR
CLASS INTERFACE
COMPARISON

Implement/Extend A class can implement any An interface can extend multiple


number of interfaces and interfaces but cannot implement any
can extend only one class. interface.

Constructor A class can have An interface can never have a constructor


constructors to initialize the as there is hardly any variable to
variables. initialize.

Variables It can be of any type The variables are final ,static

16. Define Interface


 An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
 A class that implement interface must implement all the methods declared in the interface.
To implement interface use implements keyword.

Syntax :
interface <interface_name> {
// declare constant fields
// declare methods that abstract
}

17. What is the Need of Interface


 It is used to achieve total abstraction.
 Since java does not support multiple inheritance in case of class, but by using interface it can
achieve multiple inheritance.
 It is also used to achieve loose coupling.
18. How can we extend the Interfaces in java? Can we able to extend the interfaces in java?

An interface can extend another interface in the same 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.

public interface Sports {


public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
}

SMVEC-Department of Information Technology Page 34


IT T45- Java Programming

SMVEC-Department of Information Technology Page 35

You might also like