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

20CS6205C Fund - of JAVA Programming UNIT-II

Uploaded by

Nani Lucky
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

20CS6205C Fund - of JAVA Programming UNIT-II

Uploaded by

Nani Lucky
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

20CS6205C-Fundamentals of Java Programming

UNIT- II

Chapter 4: String Handling


Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects. The Java platform provides the String class to
create and manipulate strings.
4.1 Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is
enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler
creates a String object with its value—in this case, Hello world!

As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has thirteen constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };


String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.

The String class is immutable; so that once it is created a String object cannot be changed.
The String class has a number of methods, some of which will be discussed below, that appear to
modify strings. Since strings are immutable, what these methods really do is create and return a
new string that contains the result of the operation.

String Length
1

Methods used to obtain information about an object are known as accessor methods. One
Page

accessor method that you can use with strings is the length() method, which returns the number of
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
characters contained in the string object. After the following two lines of code have been
executed, len equals 17:

String palindrome = "Dot saw I was Tod";


int len = palindrome.length();

Concatenating Strings

The String class includes a method for concatenating two strings:


string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in


"Hello," + " world" + "!"

which results in
"Hello, world!"

The + operator is widely used in print statements. For example:


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");

Which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects. For each object that is not a String,
its toString() method is called to convert it to a String.

Manipulating Characters in a String

The String class has a number of methods for examining the contents of strings, finding characters
or substrings within a string, changing case, and other tasks.

Getting Characters and Substrings by Index


2
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
You can get the character at a particular index within a string by invoking the charAt() accessor
method. The index of the first character is 0, while the index of the last character is length()-1. For
example, the following code gets the character at index 9 in a string:
String anotherPalindrome = "Niagara. O roar again!";
char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

If you want to get more than one consecutive character from a string, you can use
the substring method. The substring method has two versions, as shown in the following table:
The substring Methods in the String Class
Method Description
Returns a new string that is a substring of this string. The
String substring(int beginIndex, int first integer argument specifies the index of the first
endIndex) character. The second integer argument is the index of the
last character - 1.
Returns a new string that is a substring of this string. The
integer argument specifies the index of the first character.
String substring(int beginIndex)
Here, the returned substring extends to the end of the
original string.

The following code gets from the Niagara palindrome the substring that extends from
index 11 up to, but not including, index 15, which is the word "roar":

String anotherPalindrome = "Niagara. O roar again!";


String roar = anotherPalindrome.substring(11, 15);

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:


3
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Other Methods in the String Class for Manipulating Strings
Method Description
Searches for a match as specified by the string
argument (which contains a regular expression)
and splits this string into an array of strings
String[] split(String regex)
accordingly. The optional integer argument
String[] split(String regex, int limit)
specifies the maximum size of the returned
array. Regular expressions are covered in the
lesson titled "Regular Expressions."
CharSequence subSequence(int beginIndex, int Returns a new character sequence constructed
endIndex) from beginIndex index up untilendIndex - 1.
Returns a copy of this string with leading and
String trim()
trailing white space removed.
Returns a copy of this string converted to
String toLowerCase() lowercase or uppercase. If no conversions are
String toUpperCase() necessary, these methods return the original
string.

Searching for Characters and Substrings in a String

Here are some other String methods for finding characters or substrings within a string.
The String class provides accessor methods that return the position within the string of a specific
character or substring: indexOf() and lastIndexOf(). The indexOf() methods search forward from
the beginning of the string, and the lastIndexOf()methods search backward from the end of the
string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.

The String class also provides a search method, contains, that returns true if the string
contains a particular character sequence. Use this method when you only need to know that the
string contains a character sequence, but the precise location isn't important.

The following table describes the various string search methods.

The Search Methods in the String Class


Method Description
int indexOf(int ch) Returns the index of the first (last) occurrence of
4

int lastIndexOf(int ch) the specified character.


Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Returns the index of the first (last) occurrence of
int indexOf(int ch, int fromIndex)
the specified character, searching forward
int lastIndexOf(int ch, int fromIndex)
(backward) from the specified index.
int indexOf(String str) Returns the index of the first (last) occurrence of
int lastIndexOf(String str) the specified substring.
Returns the index of the first (last) occurrence of
int indexOf(String str, int fromIndex)
the specified substring, searching forward
int lastIndexOf(String str, int fromIndex)
(backward) from the specified index.
Returns true if the string contains the specified
boolean contains(CharSequence s)
character sequence.

CharSequence is an interface that is implemented by the String class. Therefore, you can
use a string as an argument for the contains() method.

Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In
general, they are not needed: You can create a new string by concatenation of substrings you
have removed from a string with the substring that you want to insert.

The String class does have four methods for replacing found characters or substrings, however.
They are:
Methods in the String Class for Manipulating Strings
Method Description
Returns a new string resulting from replacing
String replace(char oldChar, char newChar) all occurrences of oldChar in this string with
newChar.
Replaces each substring of this string that
String replace(CharSequence target,
matches the literal target sequence with the
CharSequence replacement)
specified literal replacement sequence.
Replaces each substring of this string that
String replaceAll(String regex, String
matches the given regular expression with the
replacement)
given replacement.
Replaces the first substring of this string that
String replaceFirst(String regex, String
matches the given regular expression with the
replacement)
given replacement.
5
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
4.2 String Buffer

A string buffer implements a mutable sequence of characters. A string buffer is like


a String, but can be modified. At any point in time it contains some particular sequence of
characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where
necessary so that all the operations on any particular instance behave as if they occur in some serial
order that is consistent with the order of the method calls made by each of the individual threads
involved.

String buffers are used by the compiler to implement the binary string concatenation
operator +. For example, the code:

x = "a" + 4 + "c"
is compiled to the equivalent of:
x = new StringBuffer().append("a").append(4).append("c")
.toString()

which creates a new string buffer (initially empty), appends the string representation of
each operand to the string buffer in turn, and then converts the contents of the string buffer to a
string. Overall, this avoids creating many temporary strings.

The principal operations on a StringBuffer are the append and insert methods, which are
overloaded so as to accept data of any type. Each effectively converts a given datum to a string and
then appends or inserts the characters of that string to the string buffer. The append method always
adds these characters at the end of the buffer; the insert method adds the characters at a specified
point.

For example, if z refers to a string buffer object whose current contents are "start", then
the method call z.append("le") would cause the string buffer to contain "startle",
whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same


effect as sb.insert(sb.length(), x).

Every string buffer has a capacity. As long as the length of the character sequence
6

contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new
Page

internal buffer array. If the internal buffer overflows, it is automatically made larger.
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Method Summary
StringBuffer append(String str)
Appends the string to this string buffer.
StringBuffer append(StringBuffer sb)
Appends the specified StringBuffer to this StringBuffer.
int capacity()
Returns the current capacity of the String buffer.
char charAt(int index)
The specified character of the sequence currently represented by the string
buffer, as indicated by the index argument, is returned.
StringBuffer delete(int start, int end)
Removes the characters in a substring of this StringBuffer.
StringBuffer deleteCharAt(int index)
Removes the character at the specified position in
this StringBuffer (shortening the StringBuffer by one character).
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified
substring.
StringBuffer insert(int offset, String str)
Inserts the string into this string buffer.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified
substring.
int length()
Returns the length (character count) of this string buffer.
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters
in the specified String.
StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the
reverse of the sequence.
7
Page

void setCharAt(int index, char ch)

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
The character at the specified index of this string buffer is set to ch.
void setLength(int newLength)
Sets the length of this String buffer.
CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int start)
Returns a new String that contains a subsequence of characters currently
contained in this StringBuffer.The substring begins at the specified index and
extends to the end of theStringBuffer.
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently
contained in this StringBuffer.
String toString()
Converts to a string representing the data in this string buffer.

4.3 String Tokenizer

The java.util.StringTokenizer class allows you to break a string into tokens. It


is simple way to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and delimeter.
String delim)
StringTokenizer(String str, creates StringTokenizer with specified string, delimeter and
String delim, boolean returnValue. If return value is true, delimiter characters are
returnValue) considered to be tokens. If it is false, delimiter characters
serve to separate tokens.

Methods of StringTokenizer class


8
Page

The 6 useful methods of StringTokenizer class are as follows:


J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

UNIT II

Chapter 5: Inheritance

5.1 Inheritance: Basics

An important concept in object-oriented programming is inheritance. It provides a way for


objects to define relationships with each other.

What is Inheritance?

Inheritance is a compile-time mechanism in Java that allows you to extend a class (called
the base class or super class) with another class (called the derived class or subclass).

The process of obtaining the data members and methods from one class to another class is
known as inheritance.

As the name suggests, inheritance means to take something that is already made. It is one
of the most important features of Object Oriented Programming. It is the concept that is used for
reusability purpose. Inheritance is the mechanism through which we can derive classes from other
classes. The derived class is called as child class or the subclass or we can say the extended class
and the class from which we are deriving the subclass is called the base class or the parent class.
To derive a class in java the keyword extends is used. To clearly understand the concept of
inheritance you must go through the following example.

For example, let's say we make a class called "Human" that represents our physical
characteristics. It's a generic class that could represent you, me or anyone in the world. Its state
keeps track of things like number of legs, number of arms, and blood type. It has behaviors like
eat, sleep, and walk. Human is good for getting an overall sense of what makes us all the same but
it can't for instance tell me about gender differences. For that we'd need to make two new class
types called "Man" and "Woman". The state and behaviors of these two classes will differ from
9

each other in a lot of ways except for the ones that their inherit from Human.
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Therefore inheritance allows us to encompass the parent class' state and behaviors into its
child. The child class can then extend the state and behaviors to reflect the differences it
represents. The most important aspect of this concept to remember is that the child class is a more
specialized version of the parent.

What Is a Super class?

In the relationship between two objects a super class is the name given to the class that is
being inherited from. It sounds like it's a super duper class but remember that it's the more generic
version. Better names to use might be base class or simply parent class.
To take a more real world example this time we could have a super class called "Person".
Its state holds the person's name, address, height and weight and has behaviors like go shopping,
make the bed, and watch TV. We could make two new classes that inherit from Person called
"Student" and "Worker". They are more specialized versions because although they have names,
addresses, watch TV and go shopping, they also have characteristics that are different from each
other. Worker could have a state that holds a job title and place of employment whereas Student
might hold data on an area of study and an institution of learning.

What Is a Subclass?

In the relationship between two objects a subclass is the name given to the class that is
inheriting from the super class. Although it sounds a little drabber, remember that it's a more
specialized version of the super class. Subclasses can also be known as derived classes or simply
child classes. In the previous example, Student and Worker are the subclasses.

Syntax of Inheritance

Create a new class as an extension of another class, primarily for the purpose of code reuse.
That is, the derived class inherits the public methods and public data of the base class. Java only
allows a class to have one immediate base class, i.e., single class inheritance. To derive a class in
java the keyword extends is used.

Class SuperClass
{
Data Members:
int x;
int y;
String z;
Methods:
public void add()
10

{
}
Page

}
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
class SubClass extends SuperClass
{
Data Members:
int a;
int b;
String k;
public void sub()
}
Types of Inheritance

1. Single inheritance
2. Multi – level inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance

1. Single inheritance: A single inheritance is one in which there exists single base class and
single derived class. In a single level of inheritance, one class extends one class only.
11

Example for Single Level Inheritance


Page

public class Inheritance {


J V D PRASAD,
ASSISTANT PROFESSOR, CSE
public static void main(String[] args) {
Math2 obj = new Math2();
obj.Add(10, 20);
obj.Subtract(80, 70);
}
}
class Math1 {

int result;

public void Add(int a, int b) { // Add two integers


result = a + b;
System.out.println(result);
}
}

class Math2 extends Math1 {

public void Subtract(int a, int b) { //Subtract a small integer from big one
if (a >= b) {
result= a - b;
} else {
result= b - a;
}
System.out.println(result);
}
}

2. Multi-level inheritance: Multi level inheritance is one in which their exists a single base
class, single derived class and multiple intermediate base classes. Multilevel Inheritance
takes place when a class extends a subclass.

Example for Multi-Level Inheritance

public class MultilevelInheritance {

public static void main(String[] args) {


C obj = new C();
obj.method1();
obj.method2();
obj.method3();
12

}
}
Page

class A {
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
public void method1() {
System.out.println("You are in method1");
}
}
class B extends A {
public void method2() {
System.out.println("You are in method2");
}
}
class C extends B {

public void method3() {


System.out.println("You are in method3");
}
}
Output
You are in method1
You are in method2
You are in method3

3. Hierarchical inheritance: Hierarchical inheritance is one in which their exists single base
class and multiple derived classes. In hierarchical type of inheritance, one class is extended
by many subclasses. It is one-to-many relationship. A realtime example is available at
dynamic binding.

Example for Hierarchical Inheritance

/*Class A is a parent class of both class B and class C i.e. one Parent class has many
sub classes. And this is the concept of Hierarchical Inheritance.*/

//A.java
public class A
{
void DisplayA()
{
System.out.println("I am in A");
}
}

//B.java
public class B extends A
{
13

void DisplayB()
{
Page

System.out.println("I am in B");
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}
}

/c.java
public class C extends A
{
void DisplayC()
{
System.out.println("I am in C");
}
}

//MainClass.java
public class MainClass
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
SubClass2 c = new SubClass2();
c.DisplayA();
c.DisplayC();

System.out.println("Calling for subclass B");


SubClass b = new SubClass();
b.DisplayA();
b.DisplayB();
}
}

Output =>
Calling for subclass C
I am in A
I am in C
Calling for subclass B
I am in A
I am in B

4. Multiple Inheritance: Multiple inheritance is one in which their exists multiple base
classes and single derived classes. In multiple inheritance, one class extends multiple
classes. Java does not support multiple inheritance but C++ supports. Java doesn’t support
"multiple inheritance" i.e. in java it is not possible that a subclass has more than one super
classes. For example in java we can't extends more than one super class for a sub class like
14

this,
Page

"public class subclass extends superclass1,superclass2, superclass3"

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Java solves this problem using "INTERFACE". Interface is just like a java class
that has variable/variables and method/methods but the only different is that interface has
abstract methods and final fields. In java it is possible to implement more than one
interfaces by a subclass using the keywords "implements".

5. Hybrid Inheritance: Hybrid inheritance is equal to combination of any available


inheritance types. "Hybrid" inheritance is a compromise between strictly single inheritance
and true multiple inheritance. It is mixture of any two of above named inheritances.

Forms of Inheritances

Inheritance is employed in a surprising variety of ways. In this section we will describe a


few of its more common uses. Note that the following list represents general abstract categories
and is not intended to be exhaustive. Furthermore, it sometime happens that two or more
descriptions are applicable to a single situation, because some methods in a single class use
inheritance in one way while others use it in another. In the following list, pay careful attention to
which uses of inheritance support the sub typing relationship and which do not.

Specialization: - The child class is a special case of the parent class; in other words, the
Child class is a subtype of the parent class.

Specification: - The parent class defines behavior that is implemented in the child class but
not in the parent class.

Construction: - The child class makes use of the behavior provided by the parent class, but
is not a subtype of the parent class.

Extension: - The child class adds new functionality to the parent class, but does not change
any inherited behavior.

Limitation: - The child class restricts the use of some of the behavior inherited from the
parent class.

Combination: - The child class inherits features from more than one parent class. Al-
though multiple inheritance is not supported directly by Java, it can be simulated in part by
classes that use both inheritance and implementation of an interface, or implement two or
more interfaces.

The Java language implicitly assumes that subclasses are also subtypes. This means
15

that an instance of a subclass can be assigned to a variable declared as the parent class type.
Page

Methods in the child class that have the same name as those in the parent class override the

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
inherited behavior. We have seen that this assumption that subclasses are subtypes is not
always.

Advantages of Inheritance

There are many important benefits of the proper use of inheritance.

Software Reusability: - When behavior is inherited from another class, the code that
provides that behavior does not have to be rewritten. This may seem obvious, but the implications
are important. Many programmers spend much of their time rewriting code they have written many
times before - for example, to search for a pattern in a string or to insert a new element into a table.
With object-oriented techniques, these functions can be written once and reused.

Increased Reliability: - Code that is executed frequently will tend to have fewer bugs then
code that executed infrequently. When the same components are used in two or more applications,
the code will be exercised more than code that is developed for a single application. Thus, bugs in
such code tend to be more quickly discovered and latter applications gain the benefit of using
components are more error free. Similarly, the costs of maintenance of shared
Components can be split among many projects.

Code Sharing: - Code sharing can occur on several levels with object-oriented techniques.
On one level, many users or projects can use the same classes. Another form of sharing occurs
when two or more classes developed by a single programmer as part of a project inherit from a
single parent class. For example, a Set and an Array may both be considered a form of Collection.
When this happens, two or more types of ob jects will share the code that they inherit. This code
needs to be written only once and will contribute only once to
the size of the resulting program.

Consistency of Interface: - When two or more classes inherit from the same superclass,
we are assured that the behavior they inherit will be the same in all cases. Thus, it is easier to
guarantee that interfaces to similar objects are in fact similar, and that the user is not presented
with a confusing collection of objects that are almost the same but behave, and are interacted with,
very differently.

Software Components: - Inheritance provides programmers with the ability to construct


reusable software components. The goal is to permit the development of new and novel
applications that nevertheless require little or no actual coding. The Java library provides a rich
collection of software components for use in the development of applications.

Rapid Prototyping: - When a software system is constructed largely out of reusable


components, development time can be concentrated on understanding the new and unusual portion
of the system. Thus, software systems can be generated more quickly and easily, leading to a style
of programming known as rapid prototyping or exploratory programming. A prototype system is
16

developed, users experiment with it, a second system is produced that is based on experience with
Page

the first, and further experimentation takes place, and so on for several iterations. Such

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
programming is particularly useful in situations where the goals and requirements of the system
are only vaguely understood when the project begins.

Information Hiding: - A programmer who reuses a software component needs only to


understand the nature of the component and its interface. It is not necessary for the programmer to
have detailed information concerning matters such as the techniques used to implement the
component. Thus, the interconnectedness between software systems is reduced. We earlier
identified the interconnected nature of conventional software as being one of the principle causes
of software complexity.

How Access Specifiers affect Inheritance

There are four Access Specifiers in Java

1. Public: When a member of a class is modified by public specifier, it can be accessed by


any other code.
2. Protected: Protected is only applicable in case of Inheritance. When a member of a class is
modified by protected, it can only be accessed by the members of its class or subclass.
3. Private: A member of a class which is modified by private specifier can only be accessed
by the member of its class.
4. Default: When you don't specify an access specifier to a member, Java automatically
specifies a default. And the members modified by default can only be accessed by any other
code in the package, but can't be accessed outside of a package.

Example for Inheritance

class parent
{
parent()
{
}

parent(int a,int b)
{
int c=a+b;
System.out.println("Sum="+c);
}
void display()
{
17

System.out.println("Return Statement");
}
Page

}
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
class child extends parent
{
child(int a,int b)
{
int c=a-b;
System.out.println("Difference="+c);
}
}
class InheritanceExample
{
public static void main(String args[])
{
child c=new child(2,1);
c.display();
}
}

5.2 Usage of Super keyword

Within a class, a field that has the same name as a field in the super class hides the super
class's field, even if their types are different. Within the subclass, the field in the super class cannot
be referenced by its simple name. Instead, the field must be accessed through super, which is
covered in the next section. Generally speaking, we don't recommend hiding fields as it makes
code difficult to read.

The super keyword in a Java instance refers to the super class of the current object.
Accessing methods or variables of an instance's super class members. If your method overrides
one of its super class's methods, you can invoke the overridden method through the use of the
keyword super. You can also use super to refer to a hidden field (although hiding fields is
discouraged).
From within a constructor, you can use the super keyword to invoke a super class's constructor.
Invocation of a super class constructor must be the first line in the subclass constructor.

For example

class Superclass {
int x, y;
18

public Superclass(int x, int y) {


this.x = x;
Page

this.y = y;
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}

public void printMethod() {


System.out.println("Printed in Superclass.");
}
}

public class Subclass extends Superclass {

public Subclass(int x, int y) {


super(x, y); //call superclass constructor
}

public void printMethod() { //overrides printMethod in Superclass


super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {

Subclass s = new Subclass(9, 8);


s.printMethod();
}

With super(), the superclass no-argument constructor is called. With super(parameter list),
the superclass constructor with a matching parameter list is called.Within the scope of a non-static
inner class, super refers to the instance super class of the non-static inner class.Within the scope of
a non-static inner class, the syntax NameOfOuterClass.super is used to reference the instance of
super class of the outer class instance.
For example

class innersuperclass {
public void myMethod(int x) {
.....
}
}

class outsuperclass {
public void myMethod()
{
}
}
19
Page

public class Outer extends outsuperclass{

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
....
public class Inner extends innersuperclass{
private int x;
....

public void myMethod(int x) {


super.myMethod(x);
//call super class (innnersuperclass) 's Method method
Outer.super.myMethod(x);
//Outer.super calls super class (outsupperclass)'s myMethod

//of an instance of Outer


}

}
}
The keyword this may be used only in the body of an instance method, instance initializer or
constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a
compile-time error occurs.

A static initializer and static method are always invoked without an instance object. You can
not using the keyword this or the keyword super in the body of a static context, otherwise results in
a compile time error

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler
automatically inserts a call to the no-argument constructor of the superclass. If the super class does
not have a no-argument constructor, you will get a compile-time error. java.lang.Object does have
such a constructor, so if Object is the only superclass, there is no problem.

class Superclass {
public Superclass(int m) {
....
}

public void printMethod() {


System.out.println("Printed in Superclass.");
}
}

public class Subclass extends Superclass {

public Subclass(int x, int y) {


//COMPILER ERROR!!!
20

//Because the super class does not have no-argument constructor


Page

this.x = x;

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
this.y = y;
}

public void printMethod() { //overrides printMethod in Superclass


super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {

Subclass s = new Subclass(9, 8);


s.printMethod();
}

}
Do not confuse by default constructor which is automatically generated by the Java
compiler for a class that no other constructors have been defined in the class. A constructor
without any parameters is known as a default constructor. The default constructor calls the no
parameter constructor in the superclass (e.g., super()) and initialize all instance variables to default
value depending on their data type. This action taken by a default constructor ensures that the
inherited state of the object is initialized properly.

If you define any constructor for your class, no default constructor is automatically created.
There is no a default constructor generated by compiler because there is a constructor (Superclass
(int m)) defined in that class.

The other form of super acts somewhat like this except that is always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
This form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass. Consider this simple class hierarchy:
// Using super to overcome name hiding.
class A {
int i;
}

// Create a subclass by extending class A.


class B extends A {
int i; // this i hides the i in A

B(int a, int b) {
super.i = a; // i in A
21

i = b; // i in B
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass " + i);
}
}

class UseSuper {
public static void main(String[] args) {
B subOb = new B(1, 2);
subOb.show();
}
}
The output appears as given below:
i in superclass: 1
i in subclass: 2

Although the instance variable i in B hides the i in A, super allows access to the i defined in the
superclass. As you will see, super can also be used to call methods that are hidden by a subclass.

5.3 Method Overriding

Method overriding in java means a subclass method overriding a super class method. Super
class method should be non-static. Subclass uses extends keyword to extend the super class. In the
example class B is the sub class and class A is the super class. In overriding methods of both
subclass and super class possess same signatures. Overriding is used in modifying the methods of
the super class. In overriding return types and constructor parameters of methods should match.
Method overriding in Java is a concept based on polymorphism OOPS concept which
allows programmer to create two methods with same name and method signature on interface and
its various implementation and actual method is called at runtime depending upon type of object at
runtime.
Method overriding allows you to write flexible and extensible code in Java because you can
introduce new functionality with minimal code change. Method overriding is different than method
overloading in Java which we have discussed above. In method overloading, only name of two
overloaded methods are same but method signature must be different while in method overriding,
method signature must be same. Method overriding represent true polymorphic behaviour, where
only name needs to be same underlying method logic can be different.

Rules of Method Overriding

1. First and most important rule regarding method overriding in Java is that you can only
22

override method in sub class. You can not override method in same class.
2. Second important rule of method overriding in Java that name and signature of method must
Page

be same in Super class and Sub class or in interface and its implementation.
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
3. Third rule to override method in Java is that overriding method cannot reduce accessibility
of overridden method in Java. For example if overridden method is public than overriding
method cannot be protected, private or package-private; But opposite is true overriding
method can increase accessibility of method in Java, i.e. if overridden method is protected
than overriding method can be protected or public.
4. You cannot override private, static and final method in Java. Private and static methods are
bonded during compile time using static binding in Java and don’t resolve during runtime.
Overriding final method in Java is compile time error. Though private and static method
can be hidden if you declare another method with same and signature in sub class.
5. Overridden method is called using dynamic binding in Java at runtime based upon type of
Object. As shown in following example of method overloading.
6. If you are extending abstract class or implementing interface than you need to override all
abstract method unless your class is not abstract. Abstract method can only be used by
using method overriding.

Example for Method Overriding

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
23

class Override {
Page

public static void main(String args[]) {

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

Difference between method overloading vs overriding in Java

Overloading vs. Overriding in Java is one of the popular java interview questions at many
companies and asked at different levels of programmers. Here are some of the silent difference
between overloading and overriding in Java. Though more important is to understand how to use
both overloading and overriding, these difference are good from interview perspective and gives
some basic idea as well:

1) First and most important difference between method overloading and overriding is that, In case
of method overloading in Java, Signature of method changes while in case of method overriding it
remain same.
2) Second major difference between method overloading vs overriding in Java is that You can
overload method in one class but overriding can only be done on subclass.
3) You cannot override static, final and private method in Java but you can overload static, final or
private method in Java.
4) Overloaded method in Java is bounded by static binding and overridden methods are subject to
dynamic binding.
5) Private and final method can also be not overridden in Java.

5.4 Dynamic Dispatch Method

Dynamic method dispatch is a mechanism by which a call to an overridden method is


resolved at runtime. This is how java implements 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 refers to. In simple words the type of object which it referred determines which
version of overridden method will be called.
24
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
It is also known as Dynamic binding, late binding and overriding as well. Dynamic binding
is a binding which happens during run time. It is also called late binding because binding happens
when program actually is running.

During run time actual objects are used for binding. For example, for “a1.method()” call in the
above picture, method() of actual object to which ‘a1’ is pointing will be called. For “a2.method()”
call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is
called dynamic binding.
25
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Static Binding Dynamic Binding

It is a binding that happens at compile


time. It is a binding that happens at run time.

Actual object is not used for binding. Actual object is used for binding.

It is also called early binding because It is also called late binding because
binding happens during compilation. binding happens at run time.

Method overloading is the best example Method overriding is the best example of
of static binding. dynamic binding.

Private, static and final methods Other than private, static and final
26

show static binding. Because, they methods show dynamic binding.


Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
cannot be overridden. Because, they can be overridden.

5.5 Using Abstract classes

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of the abstract
class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is
sub classed. This is typically how abstract classes come about during the design phase. A parent
class contains the common functionality of a collection of child classes, but the parent class itself
is too abstract to be used on its own.

Abstract Class:

Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration
somewhere before the class keyword.

/* File name : Employee.java */

public abstract class Employee


{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
27

{
System.out.println("Mailing a check to " + this.name + " " + this.address);
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */

public class AbstractDemo


{
public static void main(String [] args)
{
/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);

System.out.println("\n Call mailCheck using


Employee reference--");
e.mailCheck();
}
}

When you would compile above class then you would get following error:
28

Employee.java:46: Employee is abstract; cannot be instantiated


Page

Employee e = new Employee("George W.", "Houston, TX", 43);

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
^
1 error

Extending Abstract Class:

We can extend Employee class in normal way as follows:

/* File name : Salary.java */

public class Salary extends Employee


{
private double salary; //Annual salary

public Salary(String name, String address, int number, double salary)


{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
29

}
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.

/* File name : AbstractDemo.java */

public class AbstractDemo


{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP",
3, 3600.00);
Salary e = new Salary("John Adams", "Boston, MA",
2, 2400.00);

System.out.println("Call mailCheck using


Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using
Employee reference--");
e.mailCheck();
}
}

This would produce following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

Abstract Methods:

If you want a class to contain a particular method but you want the actual implementation of
that method to be determined by child classes, you can declare the method in the parent class as
abstract.

The abstract keyword is also used to declare a method as abstract. An abstract methods
30

consist of a method signature, but no method body.


Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Abstract method would have no definition, and its signature is followed by a semicolon, not
curly braces as follows:

public abstract class Employee


{
private String name;
private String address;
private int number;

public abstract double computePay();

//Remainder of class definition


}

Declaring a method as abstract has two results:

 The class must also be declared abstract. If a class contains an abstract method, the class
must be abstract as well.

 Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be
abstract, and any of their children must override it. Eventually, a descendant class has to
implement the abstract method; otherwise, you would have a hierarchy of abstract classes
that cannot be instantiated.

If Salary is extending Employee class then it is required to implement computePay() method


as follows:

/* File name : Salary.java */

public class Salary extends Employee


{
private double salary; // Annual salary

public double computePay()


{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
31

//Remainder of class definition


}
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Example for Abstraction

public abstract class Shape{


abstract double area();
abstract double circumference();

public void show()


{
System.out.println("Area = "+area());
System.out.println("Circumference = "+circumference());
}
}

public class Circle extends Shape{


double r;

public double area()


{
return 3.14*r*r;
}

double circumference()
{
return 2*3.14*r;
}

Circle(double radius)
{
r=radius;
}
}

public class Rectangle extends Shape{


double x,y;

double area()
{
return x*y;
}

double circumference()
32

{
Page

return 2*(x+y);

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}

Rectangle(double length, double width)


{
x = length;
y = width;
}
}

public class Geometry


{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}

5.6 Using Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

 variable
 method
 class
33
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword. You can
declare some or all of a class's methods final. You use the final keyword in a method declaration
to indicate that the method cannot be overridden by subclasses. The Object class does this—a
number of its methods are final.

You might wish to make a method final if it has an implementation that should not be
changed and it is critical to the consistent state of the object.

Methods called from constructors should generally be declared final. If a constructor calls
a non-final method, a subclass may redefine that method with surprising or undesirable results.

Note that you can also declare an entire class final. A class that is declared final cannot be
subclassed. This is particularly useful, for example, when creating an immutable class like the
String class.
1) Java final variable: If you make any variable as final, you cannot change the value of
final variable (It will be constant).

2) class Demo{
3)
4) final int MAX_VALUE=99;
5) void myMethod(){
6) MAX_VALUE=101;
7) }
8) public static void main(String args[]){
9) Demo obj=new Demo();
10) obj.myMethod();
11) }
12) }
13) Output:

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


15) The final field Demo.MAX_VALUE cannot be assigned
16)
17) at beginnersbook.com.Demo.myMethod(Details.java:6)
18) at beginnersbook.com.Demo.main(Details.java:10)

2) Java final method: If you make any method as final, you cannot override it.
34

class XYZ{
final void demo(){
Page

System.out.println("XYZ Class Method");


J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}
}

class ABC extends XYZ{


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

public static void main(String args[]){


ABC obj= new ABC();
obj.demo();
}
}
The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: 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.

3) Java final class : If you make any class as final, you cannot extend it.

final class XYZ{


}

class ABC extends XYZ{


void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
Output:

The type ABC cannot subclass the final class XYZ


35
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
UNIT-II

Chapter 6: Packages

What is Package

The main feature of OOP is its ability to support the reuse of code:
 Extending the classes (via inheritance)
 Extending interfaces
The features in basic form limited to reusing the classes within a program. What if we
need to use classes from other programs without physically copying them into the program under
development? In Java, this is achieved by using what is known as “packages”, a concept similar
to “class libraries” in other languages.
Packages are Java’s way of grouping a number of related classes and/or interfaces
together into a single unit. That means, packages act as “containers” for classes.
Packaging is used to organize classes that belong to the same files or providing similar
functionality. Apart from this, it also helps the programmer to avoid class name collision when
we use the same class name as available in another package. For example, the Date class of
java.util package is used to access the methods of the Date class. But, if we have a class name
"Date" (user defined) in our program, its name would crash with the Date class of java.util
package. To avoid this problem, we can use Package through which the "Date" class can be put
up into another package like india.mycompany.Date without collision with anyone.

Generally, classes in one package (or directory) have different functionality from another
package. For example, classes in java.io package manage the Input/output streams to read and
write data from and to files, while classes in java.net package give us the way to deal with the
network operations.

The Benefits of organizing classes into packages

 The classes contained in the packages of other programs/applications can be reused.


 In packages classes can be unique compared with classes in other packages. That two
classes in two different packages can have the same name. If there is a naming clash, then
classes can be accessed with their fully qualified name.
 Classes in packages can be hidden if we don’t want other packages to access them.
 Packages also provide a way for separating “design” from coding.
36
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Java Foundation Packages

Java provides a large number of classes groped into different packages based on their
functionality.

 The six foundation Java packages are:


 java.lang
 Contains classes for primitive types, strings, math functions, threads, and
exception
 java.util
 Contains classes such as vectors, hash tables, date etc.
 java.io
 Stream classes for I/O
 java.awt
 Classes for implementing GUI – windows, buttons, menus etc.
 java.net
 Classes for networking
 java.applet
 Classes for creating and implementing applets

Naming convention (Rules) for using the packages

 Package names are written in all lowercase to avoid conflict with the names of classes or
interfaces.

 The directory name must be same as the name of package that is created using "package"
keyword in the source file.

 Before running a program, the class path must be picked up till the main directory (or
package) that is used in the program.

 If we are not including any package in our java source file then the source file
automatically goes to the default package.

 In general, we start a package name begins with the order from top to bottom level.

 In case of the internet domain, the name of the domain is treated in reverse (prefix) order.

Creating a Package
37

The statement that is used to create a package requires a keyword called “package” and
Page

the following syntax.Java supports a keyword called “package” for creating user-defined
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
packages. The package statement must be the first statement in a Java source file (except
comments and white spaces) followed by one or more classes.

Package name is “myPackage” and classes are considred as part of this package; The
code is saved in a file called “ClassA.java” and located in a directory called “myPackage”.

Listing 1
package packagename;

The package definition must be the first statement of the java program file. Suppose we
have a program file named “Firstapplication.java” and we want to put it inside a package called
Example, then the coding that would go inside is:

Listing 2

package Example;
public class Firstapplication
{
public static void main(String a[ ])
{
System.out.println("This is my first application");
}
}
If package statement is not specified, all the classes are stored in a default unnamed package.

For creating sub packages in java, Classes in one or more source files can be part of the
same packages. As packages in Java are organized hierarchically, sub-packages can be created as
follows:

package myPackage.Math
package myPackage.secondPakage.thirdPackage

Store “thirdPackage” in a subdirectory named “myPackage\secondPackage”. Store


“secondPackage” and “Math” class in a subdirectory “myPackage”.
38
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Accessing Members from a Package

There are two ways of accessing the classes stored in packages:

 Using fully qualified class name


 java.lang.Math.sqrt(x);
 Import package and use class name directly.
 import java.lang.Math
 Math.sqrt(x);

As indicated earlier, classes in packages can be accessed using a fully qualified name or using a
short-cut as long as we import a corresponding package.

 The general form of importing package is:


 import package1[.package2][…].classname
 Example:
 import myPackage.ClassA;
 import myPackage.secondPackage
 All classes/packages from higher-level package can be imported as follows:
 import myPackage.*;

JAVA: Packages-Access control

Packages acts as a container for classes and other subordinate packages. Classes are
containers of data and code. Class is the smallest unit of abstraction. There are four categories
of visibility for class members. They are:

• Subclass in the same package


• Non-subclass in the same package
• Subclass in different packages
• Classes that are not in the same package or in the subclass

There are four access specific; public, private, protected and default or no modifier. A
public member of a class can be accessed from anywhere; within the package, outside the
package, within a subclass, as well as within a non-subclass. The only condition is that the
package must be imported into the class that uses it. Similarly a member of a class that is
declared private can be accessed only within the class but not anywhere outside the class. If no
39

access specifier is given, it is assumed to be default or friendly or package access. There is


however no special keyword to denote this. Default or package access means the member would
Page

be accessible within any class in the same package but not accessible outside the package.
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
The following table shows the accessibility of class members only. A class only has two
access levels: default and public. If a class is public then it will be accessible by any other code
but if it is default then it will be accessed by other code in the same package. The table depicts
the accessibility of class members.

The classes defined in the packages are affected by access control. The first class is a
derived class and can access only the protected and the public value.
40
Page

J V D PRASAD,
ASSISTANT PROFESSOR, CSE

You might also like