0% found this document useful (0 votes)
6 views31 pages

Java Inheritance, Overloading, and Classes

This document covers concepts of inheritance, packages, and interfaces in Java, including method overloading, passing objects as parameters, and returning objects. It explains different types of inheritance, such as single, multilevel, and hierarchical inheritance, along with the use of static, nested, and inner classes. The document also highlights the advantages of these concepts, such as code reusability and improved program structure.

Uploaded by

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

Java Inheritance, Overloading, and Classes

This document covers concepts of inheritance, packages, and interfaces in Java, including method overloading, passing objects as parameters, and returning objects. It explains different types of inheritance, such as single, multilevel, and hierarchical inheritance, along with the use of static, nested, and inner classes. The document also highlights the advantages of these concepts, such as code reusability and improved program structure.

Uploaded by

dhivyabt2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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: Packages – Packages and Member Access
–Importing Packages – Interfaces.

2.1 OVERLOADING METHODS


Method overloading is a feature in Java that allows a class to have more than one method with the same name,
as long as their parameter lists are different. This can mean a difference in the number of parameters, the type
of parameters, or both. Method overloading is also known as compile-time polymorphism or static
polymorphism/Early Binding.
Different Ways of Method Overloading in Java
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
1. Changing the Number of Parameters
 Method overloading can be achieved by changing the number of parameters while passing to
different methods.
Example Program: (noofarg,java)
class Product {
public int multiply(int a, int b)
{ int prod = a * b; Output:
return prod; } C:\java programs>javac [Link]
public int multiply(int a, int b, int c) C:\java programs>java noofarg
{ int prod = a * b * c; Product of the two integer value :2
return prod; Product of the three intger value :6
}}
class noofarg {
public static void main(String[] args)
{ Product ob = new Product();
int prod1 = [Link](1, 2);
[Link]( "Product of the two integer

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 1 PREPARED BY


DHIVYA.G,AP/CSE
value :" + prod1);
int prod2 = [Link](1, 2, 3);
[Link]( "Product of the three integer
value :" + prod2);
}}
2. Changing Data Types of the Arguments
 Methods can be overloaded with same name but have different parameter types.
Example Program: ([Link])
class Product {
public int Prod(int a, int b, int c)
{ int prod1 = a * b * c; Output:
return prod1; } C:\java programs>javac [Link]
public double Prod(double a, double b, double c) C:\java programs>java diffdata
{ double prod2 = a * b * c;
return prod2; } Product of the three integer value :6
} Product of the three double value :6.0
class diffdata {
public static void main(String[] args)
{
Product obj = new Product();
int prod1 = [Link](1, 2, 3);
[Link]( "Product of the three
integer value :" + prod1);
double prod2 = [Link](1.0, 2.0, 3.0);
[Link]( "Product of the three
double value :" + prod2);
}
}
3. Changing the Order of the Parameters of Methods
 Method overloading can also be implemented by rearranging the parameters of two or more
overloaded methods.
Example Program:
class Student {

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 2 PREPARED BY


DHIVYA.G,AP/CSE
public void StudentId(String name, int roll_no)
{ [Link]("Name :" + name + " "+ "Roll- Output:
No :" + roll_no); } C:\javaprograms>javac
public void StudentId(int roll_no, String name) [Link]
{ [Link]("Roll-No :" + roll_no + " "+ C:\java programs>java
"Name :" + name); } orderofparameter
} Name :Sandhiya Roll-No :1
class orderofparameter{ Roll-No :2 Name :Kamlesh
public static void main(String[] args)
{
Student obj = new Student();
[Link]("Sandhiya", 1);
[Link](2, "Kamlesh");
}
}
Advantages of Method Overloading
 Improves the Readability and reusability of the program.
 Reduces the complexity of the program.
 Perform a task efficiently and effectively.
2.2 OBJECTS AS PARAMETERS
 Objects, like primitive types, can be passed as parameters to methods in Java.
 When passing an object as a parameter to a method, a reference to the object is passed rather than a
copy of the object itself.
 This means that any modifications made to the object within the method will have an impact on the
original object.

Example Program: ([Link])


class ObjectParameter {
private int roll_no;
private String name; Output:
public ObjectParameter(int roll_no, String name) { C:\javaprograms>javac
this.roll_no = roll_no; [Link]
[Link]= name; C:\java programs>java ObjectParameter
} Roll no: 20

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 3 PREPARED BY


DHIVYA.G,AP/CSE
// Method that takes an object as a parameter Name: World
public void display(ObjectParameter obj) { Roll no: 10
[Link]("Roll no: " + obj.roll_no); Name: Hello
[Link]("Name: " + [Link]);
}
public static void main(String[] args) {
ObjectParameter obj1 = new ObjectParameter(10, "Hello");
ObjectParameter obj2=new ObjectParameter(20, "World");
// Passing obj2 as a parameter to the displayAttributes
method of obj1
[Link](obj2);
// Passing obj1 as a parameter to the displayAttributes
method of obj2
[Link](obj1);
}}
Advantages of Passing an Object as a Parameter
1. Flexibility
2. Reusability of Code
3. Encapsulation
2.3 RETURNING OBJECTS
 Similar to returning primitive types, Java methods can also return objects.
 A reference to the object is returned when an object is returned from a method, and the calling method
can use that reference to access the object.
Example Program: ([Link])
class ObjectReturn {
int a;
ObjectReturn(int i) { a = i; } Output:
ObjectReturn incrByTen() C:\java programs>javac
{ [Link]
ObjectReturn temp=new ObjectReturn(a + 10); C:\java programs>java ReturnObject
return temp; } ob1.a: 2
} ob2.a: 12
public class ReturnObject{

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 4 PREPARED BY


DHIVYA.G,AP/CSE
public static void main(String args[])
{
ObjectReturn ob1 = new ObjectReturn(2);
ObjectReturn ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
}}

2.4 STATIC, NESTED AND INNER CLASSES


 In Java, it is possible to define a class within another class, such classes are known as nested classes.
 The scope of a nested class is bounded by the scope of its enclosing class.
 A nested class has access to the members of its enclosing class, including private members. But the
enclosing class does not have access to the member of the nested class.
 A nested class is also a member of its enclosing class.
 Nested classes are divided into two categories:
1. static nested class: Nested classes that are declared static are called static nested classes.
2. inner class: An inner class is a non-static nested class.
1. Inner Class/Non-Static Nested ClassInner Class
 A non-static nested class is a class within another class.
 It has access to members of the enclosing class (outer class) even if they are declared private. It is
commonly known as inner class.
 It must instantiate the outer class first, in order to instantiate the inner class.
Syntax of Inner class:
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 5 PREPARED BY


DHIVYA.G,AP/CSE
Instantiating an Inner Class: Two Methods:
1. Instantiating an Inner class from outside the outer class:
To instantiate an instance of an inner class, you must have an instance of the outer
class.
Syntax:
[Link] objectName=[Link] InnerClass();
2. Instantiating an Inner Class from Within Code in the Outer Class:
 From inside the outer class instance code, use the inner class name in the
normal way:
Syntax:
InnerClassName obj=new InnerClassName();
Advantage of Java inner classes
1. Access all the members (data members and methods) of the outer class, including private.
2. More readable and maintainable code.
3. Requires less code to write.
Example Program: ([Link])
class TestMemberOuter1
{
private int data=30;
Output:
class Inner
{ C:\java programs>
void msg() javac [Link]
{

[Link]("data is "+data); C:\java programs>java innerouterclass


} data is 30
}
}
class innerouterclass
{
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
[Link] in=[Link] Inner();
[Link]();
}
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 6 PREPARED BY


DHIVYA.G,AP/CSE
Example Program: ([Link])
class localInner1
{
private int data=30;//instance variable
Output:
void display()
{ C:\java programs>javac [Link]
int value=50;
class Local
C:\java programs>java innerclass
{
void msg() 30
{ 50
[Link](data);
[Link](value);
}
}
Local l=new Local();
[Link]();
}
}
class innerclass
{
public static void main(String args[])
{
localInner1 obj=new localInner1();
[Link]();
}
}
[Link] nested class
 A static class i.e. created inside a class is called static nested class in java.
 It cannot access non-static data members and methods. It can be accessed by outer class name.
 It can access static data members of outer class including private.
 Static nested class cannot access non-static (instance) data member or method.
Example Program: ([Link])
class TestOuter1
{
static int data=30; Output:
static class Inner C:\java programs>javac [Link]
{ C:\java programs>java staticclass
void msg() data is 30

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 7 PREPARED BY


DHIVYA.G,AP/CSE
{
[Link]("data is "+data);
}}}
class staticclass
{
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}}

INHERITANCE
2.5 INHERITANCE BASICS
 Inheritance is a process of deriving a new class from existing class, also called as
“extending a class”. When an existing class is extended, the new (inherited) class has all
the properties and methods of the existing class and also possesses its own
characteristics.
 The class whose property is being inherited by another class is called “base
class”(or) “parent class” (or) “super class”.
 The class that inherits a particular property or a set of properties from the base
class is called “derived class” (or) “child class” (or) “sub class”.
 Subclasses of a class can define their own unique behaviors and yet share some of the
same functionality of the parent class.
Advantages
 Reusability of Code
 Effort and Time Saving
 Increased Reliability
“extends” KEYWORD:

 The extends keyword is used to inherit a class from existing class.

Syntax:

[access_specifier] class subclass_name extends superclass_name

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 8 PREPARED BY


DHIVYA.G,AP/CSE
{

// body of class

}
Characteristics of Class Inheritance:
1. A class cannot be inherited from more than one base class.
2. Sub class can access only the non-private members of the super class.
3. Private data members of a super class are local only to that class.
4. Protected features in Java are visible to all subclasses as well as all other classes in the same
package.

TYPES OF INHERITANCE
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 9 PREPARED BY


DHIVYA.G,AP/CSE
1. SINGLE INHERITANCE
 The process of creating only one subclass from only one super class is known as
Single Inheritance.
 Only two classes are involved in this inheritance.
 The subclass can access all the members of super class.
Example Program: ([Link])
class A
{
void show()
{
[Link]("Class A");
}}
class B extends A
{ Output:
void disp() C:\java programs>javac [Link]
{
C:\java programs>java Main
[Link]("Class B");
}}
class Main Class A
{ Class B
public static void main(String args[])
{
B b=new B();
[Link]();

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 10 PREPARED BY


DHIVYA.G,AP/CSE
[Link]();}}
2. MULTILEVEL INHERITANCE
 The process of creating a new sub class from an already inherited sub class is known as Multilevel
Inheritance.
 Multiple classes are involved in inheritance, but one class extends only one.
 The lower most subclass can make use of all its super classes members.
Example Program: ([Link])
import [Link].*;
class A
{
void show()
{
[Link]("Class A");
}
} Output:
class B extends A C:\java programs>javac [Link]
{
C:\java programs>java Main
void disp()
{ Class A
[Link]("Class B"); Class B
} Class C
}
class C extends B
{
void display()
{
[Link]("Class C");
}
}
class Main
{
public static void main(String args[])
{
C c=new C();
[Link]();
[Link]();
[Link]();
}
}
3. HIERARCHICAL INHERITANCE

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 11 PREPARED BY


DHIVYA.G,AP/CSE
 The process of creating more than one sub classes from one super class is called Hierarchical
Inheritance.
Example Program: ([Link])
class A
{
void show()
{
[Link]("Class A");
}}
class B extends A
{ Output:
void disp() C:\java programs>javac [Link]
{
C:\java programs>java Main
[Link]("Class B CHILD OF A");
}} Class A
class C extends B Class B CHILD OF A
{ Class A
void display()
{ Class C CHILD OF A
[Link]("Class C CHILD OF A");
}}
class Main
{
public static void main(String args[])
{
B b=new B();
[Link]();
[Link]();
C c=new C();
[Link]();
[Link]();
}}
Why multiple inheritance is not supported in java?
 To reduce the complexity and simplify the language, multiple inheritances 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.

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 12 PREPARED BY


DHIVYA.G,AP/CSE
2.6 SUPER KEYWORD
 Super is a special keyword that directs the compiler to invoke the superclass members. It is used to
refer to the parent class of the class in which the keyword is used.
 super keyword is used for the following three purposes:
1. To invoke super class constructor.
2. To invoke super class members variables.
3. To invoke super class methods.
1. Invoking a super class constructor:
 Super as a standalone statement(ie. super()) represents a call to a constructor of the super class.
 A subclass can call a constructor method defined by its super class by use of the following form of
super:
Syntax:
super(); or
super(parameter-list);
 Here, parameter-list specifies any parameters needed by the constructor in the superclass.
 super( ) must always be the first statement executed inside a subclass constructor.
2. Invoking a superclass members (variables and methods):
i. Accessing the instance member variables of the superclass:
Syntax:
[Link];
ii. Accessing the methods of the superclass:
Syntax:
[Link]();
 This call is particularly necessary while calling a method of the super class that is overridden in the
subclass.
 If a parent class contains a finalize() method, it must be called explicitly by the derived class’s
finalize() method.
Example Program: ([Link])
class A// super class
{
int i;
A(String str) //superclass constructor
{
[Link](" Welcome to "+str);
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 13 PREPARED BY


DHIVYA.G,AP/CSE
void show() //superclass method Output:
{ C:\java programs>javac [Link]
[Link](" Thank You!");
C:\java programs>java UseSuper
}
} Welcome to Java Programming
class B extends A i in superclass : 1
{
i in subclass : 2
int i; // hides the superclass variable 'i'.
B(int a, int b) // subclass constructor Thank You!
{
super("Java Programming");
super.i=a;
i=b;
}
void show()
{
[Link](" i in superclass : "+super.i);
[Link](" i in subclass : "+i);
[Link](); // invoking superclass method
}
}
public class UseSuper {
public static void main(String[] args) {
B objB=new B(1,2);
[Link]();
}
}

2.7 METHOD OVERRIDING


 The process of a subclass redefining a method contained in the superclass (with the same method
signature) is called Method Overriding.
Rules for Method Overriding:
1. The method must have the same name as in the parent class.
2. The method must have the same parameter as in the parent class.
3. A method declared final cannot be overridden.
4. A method declared static cannot be overridden but can be re-declared.
5. Constructors cannot be overridden.
Advantage of Method Overriding:
 Method Overriding is used to provide specific implementation of a method.
 Method Overriding is used for Runtime Polymorphism

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 14 PREPARED BY


DHIVYA.G,AP/CSE
Example Program: ([Link])
class animal
{
void sound()
{
[Link]("Animal Sound");
}
}
Output:
class dog extends animal
{ C:\java programs>javac [Link]
void sound() C:\java programs>java methodoverride
{
Animal Sound
[Link]();
[Link]("Barking Sound"); Barking Sound
}
}
class methodoverride
{
public static void main(String args[])
{
dog d=new dog();
[Link]();
}
}

2.8 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.
 It allows objects to take on multiple forms, and one way it achieves this is through a mechanism
called dynamic method dispatch/ runtime polymorphism.
 When an overridden method is called by a reference, java determines which version of that method to
execute based on the type of object it refer to.
Advantages:
 It is a powerful feature because it allows flexibility to write code.
 Promotes code reusability and modularity
 By allowing objects to take on multiple forms.
Example Program: ([Link])
class A {

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 15 PREPARED BY


DHIVYA.G,AP/CSE
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
void callme() {
[Link]("Inside B's callme method");
}}
class C extends A
{
void callme() {
Output:
[Link]("Inside C's callme method");
}} C:\java programs>javac [Link]
class Dispatch C:\java programs>java Dispatch
{ Inside A's callme method
public static void main(String args[])
{ Inside B's callme method
A a=new A(); //object of type A Inside C's callme method
B b=new B(); //object of type B
C c=new C(); //object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
// dynamic method dispatch
[Link](); // calls A’s version of callme()
r = b; // r refers to an B object
[Link](); // calls B’s version of callme()
r = c; // r refers to an C object
[Link](); // calls C’s version of callme()
}
}

2.9 ABSTRACT CLASSES


Abstraction:
 Abstraction is a process of hiding the implementation details and showing only the essential features
to the user.
 Ex: sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 16 PREPARED BY


DHIVYA.G,AP/CSE
2. Interface (100%)
Abstract Classes:
 A class that is declared as abstract is known as abstract class. Abstract classes cannot be instantiated,
but they can be subclasses.
Syntax:
abstract class <class_name>
{
Member variables;
Concrete methods { }
Abstract methods();
}

Abstract Methods:
 A method that is declared as abstract and does not have implementation is known as abstract method.
It acts as placeholder methods that are implemented in the subclasses.
 If a class contains at least one abstract method then compulsory should declare a class as abstract
Syntax:
abstract class classname
{
abstract return_type <method_name>(parameter_list);//no braces

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 17 PREPARED BY


DHIVYA.G,AP/CSE
{
//no function body
}
……..
}
Ex: Write a Java program to create an abstract class named Shape that contains 2 integers and an
empty method named PrintArea(). Provide 3 classes named Rectangle, Triangle and Circle such that
each one of the classes extends the class Shape. Each one of the classes contain only the method
PrintArea() that prints the area of the given shape. (AU ND 2019)
Example Program: ([Link])
abstract class shape
{
int x, y;
abstract void printArea();
}
class Rectangle extends shape
{
void printArea()
{
[Link]("Area of Rectangle is " + x * y);
}
Output:
}
class Triangle extends shape
{ C:\java programs>javac [Link]
void printArea() C:\java programs>java abs
{
[Link]("Area of Triangle is " + (x * y) / 2); Area of Rectangle is 200
} Area of Triangle is 525
} Area of Circle is 12
class Circle extends shape
{
void printArea()
{
[Link]("Area of Circle is " + (22 * x
* x) / 7);
}
}
class abs
{
public static void main(String[] args)

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 18 PREPARED BY


DHIVYA.G,AP/CSE
{
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
[Link]();
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
[Link]();
Circle c = new Circle();
c.x = 2; [Link]();
}
}

2.10 FINAL WITH INHERITANCE


 Final is a keyword or reserved word in java used for restricting some functionality.
 It can be applied to member variables, methods, class and local variables in Java.
Final keyword has three uses:
1. For declaring variable – to create a named constant. A final variable cannot be changed once it is
initialized.
2. For declaring the methods – to prevent method overriding. A final method cannot be overridden
by subclasses.
3. For declaring the class – to prevent a class from inheritance. A final class cannot be inherited.
1. Final Variable:
 Any variable either member variable or local variable modified by final keyword is called final
variable.
 The final variable can be assigned only once.
 The value of the final variable will not be changed during the execution of the program.
 If an attempt is made to alter the final variable value, the java compiler will throw an error message.
Syntax:
final data_type variable_name = value;
Example:
final int PI=3.14;
Example Program: ([Link])
class Bike Output:
{ C:\java programs>javac [Link]
final int speedlimit=90;//final variable

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 19 PREPARED BY


DHIVYA.G,AP/CSE
void run( ) [Link][Link] error: cannot assign a value to final
{ variable speedlimit
speedlimit=400;
speedlimit=400;
}}
class Finalvar ^
{ 1 error
public static void main(String args[])
{
Bike obj=new Bike();
[Link]();
}
}
[Link] Methods:
 Final keyword can also be applied to methods.
 A java method with final keyword is called final method and it cannot be overridden in sub-class.
 If a method is defined with final keyword, it cannot be overridden in the subclass and its behaviour
should remain constant in sub-classes.
Syntax:
final return_type function_name(parameter_list)
{
// method body
}
Example Program: ([Link])
class Bike Output:
{ C:\java programs>javac [Link]
final void run()
[Link][Link] error: run() in Honda cannot
{
[Link]("running"); override run() in Bike
} void run()
}
^
class Honda extends Bike
{ overridden method is final
void run() 1 error
{
[Link]("running safely with
100kmph");
}
}
class Finalmthd
{

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 20 PREPARED BY


DHIVYA.G,AP/CSE
public static void main(String args[])
{
Honda honda= new Honda();
[Link]();
}
}
3. Final Classes:
 Java class with final modifier is called final class in Java and they cannot be sub-classed or
inherited.
Syntax:
final class class_name
{
// body of the class
}
Example Program: ([Link])
final class Bike Output:
{ C:\java programs>javac [Link]
}
[Link][Link] error: cannot inherit from
class Honda1 extends Bike
{ final Bike
void run() class Honda1 extends Bike
{
^
[Link]("running safely with
100kmph"); 1 error
}
}
class Finalclass
{
public static void main(String args[])
{
Honda1 honda= new Honda1();
[Link]();
}
}

PACKAGES
2.11 PACKAGES
 A java package is a group of similar types of classes, interfaces and sub-packages.

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 21 PREPARED BY


DHIVYA.G,AP/CSE
 Package in java can be categorized in two form,

 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Import a Class
Advantage of Java Package
1) To categorize the classes and interfaces so that they can be easily maintained.
2) Provides access protection.
3) Removes naming collision.
1. Built-in Packages
 These packages consist of a large number of classes which are a part of Java API.
 Some of the commonly used built-in packages are:
 [Link]: Contains language support classes. This package is automatically imported.
 [Link]: Contains classes for supporting input / output operations.
 [Link]: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
 [Link]: Contains classes for creating Applets.
 [Link]: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
 [Link]: Contain classes for supporting networking operations.
Example Program: ([Link])
import [Link]; Output:
class MyClass { C:\java programs>javac [Link]
public static void main(String[] args) { C:\java programs>java MyClass
Scanner myObj = new Scanner([Link]); Enter username
[Link]("Enter username"); Username is: divya
String userName = [Link]();
[Link]("Username is: " +
userName);
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 22 PREPARED BY


DHIVYA.G,AP/CSE
}
 [Link] is a package, while Scanner is a class of the [Link] package.
2. User-defined packages:
 These are the packages that are defined by the user.
 First we create a directory myPackage (name should be same as the name of the package).
 Then create the MyClass inside the directory with the first statement being the package names.
Creating User Defined Packages:
 Java package created by user interface are known as user-defined packages.
 When creating a package, you should choose a name for the package.
 The package statement should be the first line at the top of every source file
 There can be only one package statement in each source file
Syntax:
package package_name.[sub_package_name];
public class classname
{
……..
……..
}
Steps involved in creating user-defined package:
1. Create a directory which has the same name as the package.
2. Include package statement along with the package name as the first statement in the
program.
3. Write class declarations.
4. Save the file in this directory as “name of [Link]”.
5. Compile this file using java compiler.
2.11.1 IMPORTING PACKAGES/ACCESSING A PACKAGE
 The import keyword is used to make the classes and interface of another package accessible to
the current package.

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 23 PREPARED BY


DHIVYA.G,AP/CSE
Syntax:
import package1[.package2][.package3].classname or *;
 There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
 If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
2) Using [Link]
 If you import [Link] then only declared class of this package will be accessible.
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.
Example :
[Link] (create a folder named “pack” in F:\ and save )
package pack;
public class greeting{
public static void greet()
{
}
Example Program: ([Link])
package Factorial;
public class FactorialClass
{
public int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1); } }

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 24 PREPARED BY


DHIVYA.G,AP/CSE
import [Link].*; Output:
// using import package.* C:\java programs>javac [Link]
import [Link]; C:\java programs>java ImportClass
// using import [Link]; Enter a Number:
import [Link]; 5
public class ImportClass Hello! Good Morning!
{ Factorial of 5 = 120
public static void main(String[] arg) Power(5,2) = 25.0
{
int n;
Scanner in=new Scanner([Link]);
[Link]("Enter a Number: ");
n=[Link]();
[Link] p1=new [Link]();
// using fully qualified name
[Link]();
FactorialClass fobj=new FactorialClass();
[Link]("Factorial of "+n+" = "+[Link](n));
[Link]("Power("+n+",2)="+[Link](n,2));
}
}

2.12 PACKAGES AND MEMBER ACCESS


Member Access Control

 Java provides several access modifiers to control access to classes, methods, and fields:
[Link]: The member is accessible from any other class.
public class MyClass {

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 25 PREPARED BY


DHIVYA.G,AP/CSE
public void myMethod() {
// Accessible everywhere
}
}
[Link]: The member is accessible within its own package and by subclasses.

public class MyClass {


protected void myMethod() {
// Accessible within package and subclasses
}
}
[Link] (Package-Private): If no access modifier is specified, the member is accessible only within its
own package.
class MyClass {
void myMethod() {
// Accessible within package
}
}
[Link]: The member is accessible only within its own class.
public class MyClass {
private void myMethod() {
// Accessible only within this class
}
}
Example Program: ([Link])
package MyPack;
public class FirstClass
{
public String i="I am public variable";
protected String j="I am protected variable";
private String k="I am private variable";
String r="I dont have any modifier";
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 26 PREPARED BY


DHIVYA.G,AP/CSE
Example Program: ([Link]) Output:
package MyPack2; C:\java programs>javac [Link]
import [Link]; C:\java programs>java SecondClass
class SecondClass extends FirstClass { I am public variable
void method() I am protected variable
{
[Link](i);
[Link](j);
[Link](k);
// Error: k has private access in FirstClass
[Link](r);
/* Error: r is not public in FirstClass
cannot be accessed from outside package */
}
public static void main(String arg[])
{
SecondClass obj=new SecondClass();
[Link]();
}
}

2.13 INTERFACES
 An interface is a collection of method definitions without implementations and constant values.
 It is a blueprint of a class.
 It has static constants and abstract methods.
 The keyword “interface” is used to define an interface.
Interface Uses:
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
Advantage:
 Writing flexible and maintainable code.
 Declaring methods that one or more classes are expected to implement.

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 27 PREPARED BY


DHIVYA.G,AP/CSE
Syntax:
access_specifier interface interface_name
{
Data_type variable=const;
Return_type method_name(parameter_list);
}
Understanding relationship between classes and interfaces

Implementing Interfaces (“implements” keyword):


 Once an interface has been defined, one or more classes can implement that interface by using
implements keyword to implement an interface.
Syntax:
[access_specifier] class class_name [extends superclassName] implements
interface_name1, interface_name2…
{
//implementation code and code for the method of the interface
}
Rules:
1) If a class implements an interface, then it must provide implementation for all the methods defined
within that interface.
2) A class can implement more than one interfaces by separating the interface names with comma(,).
3) A class can extend only one class, but implement many interfaces.
4) An interface can extend another interface, similarly to the way that a class can extend another
class.
5) If a class does not perform all the behaviors of the interface, the class must declare itself as
abstract.
1. Single Interface With Multiple Classes:

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 28 PREPARED BY


DHIVYA.G,AP/CSE
EXAMPLE PROGRAM: ([Link]) Output:
interface Animal { C:\java programs>javac [Link]
public void animalSound(); // No Function body
C:\java programs>java Main
public void character(); // No Function body
} The pig says: wee wee
class Pig implements Animal { Piglet
public void animalSound() {
The Dog says: wow wow
[Link]("The pig says: wee wee");
} Scooby
public void character() {
[Link]("Piglet"); }
}
class Dog implements Animal {
public void animalSound() {
[Link]("The Dog says: wow wow");
}
public void character() {
[Link]("Scooby");
}}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
[Link]();
[Link]();
Dog myDog = new Dog();
[Link]();
[Link]();
}}
[Link] Interface :
EXAMPLE PROGRAM: Output:
([Link]) C:\javaprograms>javac
interface Printable{
[Link]
void print();
} C:\java programs>java multipleinterface
interface Showable{ Hello
void show();
Welcome
}
class A implements Printable,Showable
{
public void print()
{[Link]("Hello");}
public void show()

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 29 PREPARED BY


DHIVYA.G,AP/CSE
{[Link]("Welcome");
}
class multipleinterface
public static void main(String args[]){
A obj = new A();
[Link]();
[Link]();
} }
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.
Syntax:
[accessspecifier] interface InterfaceName extends interface1, interface2,…..
{
Code for interface
}
EXAMPLE PROGRAM: Output:
([Link]) C:\javaprograms>javac
interface Printable [Link]
{void print(); C:\java programs>java extendsinterface
}
Hello
interface Showable extends Printable
{ Welcome
void show();
}
class TestInterface implements Showable{
public void print(){[Link]("Hello");}
public void show()
{[Link]("Welcome");}
}
class extendsinterface
{public static void main(String args[])
{
TestInterface obj = new TestInterface();
[Link]();
[Link]();
}

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 30 PREPARED BY


DHIVYA.G,AP/CSE
}
-----------------------------------@@@@@@@@@@@@@@@--------------------------------------------------------

SRRCET/CSE/III SEM/CS3391_OOPS/UNIT II 31 PREPARED BY


DHIVYA.G,AP/CSE

You might also like