20CS6205C Fund - of JAVA Programming UNIT-II
20CS6205C Fund - of JAVA Programming UNIT-II
UNIT- II
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:
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:
Concatenating Strings
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");
which results in
"Hello, world!"
Which prints
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.
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.
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":
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.
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.
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.
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
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".
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
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.
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.
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.
UNIT II
Chapter 5: Inheritance
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.
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
int result;
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.
}
}
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 {
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.
/*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();
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
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".
Forms of Inheritances
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
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.
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.
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();
}
}
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
this.y = y;
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}
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
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
....
public class Inner extends innersuperclass{
private int x;
....
}
}
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) {
....
}
this.x = x;
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
this.y = y;
}
}
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;
}
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.
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.
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.
// 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
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
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.
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
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
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
cannot be overridden. Because, they can be overridden.
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.
{
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.
When you would compile above class then you would get following error:
28
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
^
1 error
}
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.
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
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
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:
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.
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Example for Abstraction
double circumference()
{
return 2*3.14*r;
}
Circle(double radius)
{
r=radius;
}
}
double area()
{
return x*y;
}
double circumference()
32
{
Page
return 2*(x+y);
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
}
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:
2) Java final method: If you make any method as final, you cannot override it.
34
class XYZ{
final void demo(){
Page
3) Java final class : If you make any class as final, you cannot extend it.
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.
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.
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
J V D PRASAD,
ASSISTANT PROFESSOR, CSE
Accessing Members from a Package
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.
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:
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
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