JP Unit 1
JP Unit 1
Course Outcomes:
Able to solve real world problems using OOP techniques.
Able to understand the use of abstract classes.
Able to solve problems using java collection framework and I/o classes.
Able to develop multithreaded applications with synchronization.
Able to develop applets for web applications.
Able to design GUI based applications
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and Communities,
messages and methods, Responsibilities, Classes and Instances, Class Hierarchies-
Inheritance, Method binding, Overriding and Exceptions, Summary of Object-Oriented
concepts. Java buzzwords, An Overview of Java, Data types, Variables and Arrays,
operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors,
Creating Multilevel hierarchy, super uses, using final with inheritance, Polymorphism-ad
hoc polymorphism, pure polymorphism, method overriding, abstract classes, Object
class, forms of inheritance- specialization, specification, construction, extension,
limitation, combination, benefits of inheritance, costs of inheritance.
UNIT - II
Packages- Defining a Package, CLASSPATH, Access protection, importing packages.
Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying
interfaces, variables in interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams,
Reading console Input and Writing Console Output, File class, Reading and writing Files,
Random access file operations, The Console class, Serialization, Enumerations, auto
boxing, generics.
UNIT - III
Exception handling - Fundamentals of exception handling, Exception types,
Termination or resumptive models, Uncaught exceptions, using try and catch, multiple
catch clauses, nested try statements, throw, throws and finally, built- in exceptions,
creating own exception sub classes.
UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The
Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array
Deque. Accessing a Collection via an Iterator, Using an Iterator, The For-Each
alternative, Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The
Legacy Classes and Interfaces- Dictionary, Hashtable, Properties, Stack, Vector, More
Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture,
components, containers. Understanding Layout Managers, Flow Layout, Border Layout,
Grid Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners,
Event classes, Handling mouse and keyboard events, Adapter classes, Inner classes,
Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets
and Applications, passing parameters to applets. Creating a Swing Applet, Painting in
Swing, A Paint example, Exploring, Swing Controls- JLabel and Image Icon, JText Field,
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed
Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
TEXT BOOKS:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education
(India) Pvt.Ltd.
2. Understanding Object-Oriented Programming with Java, updated edition, T. Budd,
Pearson Education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J. Nino and F.A. Hosch,
John Wiley & sons
2. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
3. Object Oriented Programming through Java, P. Radha Krishna, University Press.
4. Programming in Java, S. Malhotra, S. Chudhary, 2nd edition, Oxford Univ. Press.
5. Java Programming and Object-oriented Application Development, R. A. Johnson,
Cengage Learning.
UNIT-I
Object-Oriented Thinking- A way of viewing world – Agents and Communities,
messages and methods, Responsibilities, Classes and Instances, Class Hierarchies-
Inheritance, Method binding, Overriding and Exceptions, Summary of Object-Oriented
concepts. Java buzzwords, An Overview of Java, Data types, Variables and Arrays,
operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors,
Creating Multilevel hierarchy, super uses, using final with inheritance, Polymorphism-ad
hoc polymorphism, pure polymorphism, method overriding, abstract classes, Object
class, forms of inheritance- specialization, specification, construction, extension,
limitation, combination, benefits of inheritance, costs of inheritance.
Object-oriented programming has been a hot topic for over a decade, and more recently
Java has become the commonly perceived embodiment of object-oriented ideas. Object-
oriented programming is frequently referred to as a new programming paradigm. The
word paradigm originally meant example, or model.
To solve the problem, let me call zomato (an agent in food delivery community), tell them
the variety and quantity of food and the hotel name from which I wish to deliver the food
to my family members. Look at the following image.
In our example, the online food delivery system is a community in which the agents are
zomato and set of hotels. Each hotel provides a variety of services that can be used by
other members like zomato, me and my family in the community.
message was sent. In response to the message, the receiver performs some method to
carry out the request. Every message may include any additional information as
arguments.
In our example, I send a request to zomato with a message that contains food items, the
quantity of food, and the hotel details. The receiver uses a method to food get delivered
to my home.
Responsibilities:
In object-oriented programming, behaviors of an object described in terms of
responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered
to my family). The agent (zomato) is free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.
Object: Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.
Encapsulation: Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are
private here.
Inheritance: Inheritance is the process of acquiring properties and behaviors from one
object to another object or one class to another class. In inheritance, we derive a new
class from the existing class. Here, the new class acquires the properties and behaviors
from the existing class. In the inheritance concept, the class which provides properties is
called as parent class and the class which receives the
properties is called as child class. The parent class is also
known as base class or super class. The child class is also
known as derived class or sub class.
Benefits of Inheritance:
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be re-factored to move the
common code up to a mutual super class. This also tends to result in a better
organization of code and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that
inherit from a common super class can be used interchangeably. If the return type of a
method is super class
Reusability: facility to use public methods of base class without rewriting the same.
Extensibility: extending the base class logic as per business logic of the derived
class.
Data hiding: base class can decide to keep some data private so that it cannot be
altered by the derived class
Program is divided into small chunks based Program is divided into objects
on the functions. depending on the problem.
Functions are more important than data in The main priority is data rather than
a program. functions in a program.
Different parts of a program are The functions of the objects are linked
interconnected via parameter passing. via message passing.
Exception Handling is not present. Exception Handling is done with Try and
Catch block.
Java Buzz Words: Java is the most popular object-oriented programming language.
Java has many advanced features, a list of key features is known as Java Buzz Words.
The java team has listed the following terms as java buzz words.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple: Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java follow basic programming language C and object-
oriented programming concepts are similar to C++. In a java programming language,
many complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes
java simpler.
Secure: Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.
Portable: Portability is one of the core features of java which enables the java programs
to run on any computer or operating system. For example, an applet developed using
java runs on a wide variety of CPUs, operating systems, and browsers connected to the
Internet.
Robust: Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage collector),
java is a strictly typed language, it has a strong set of exception handling mechanism,
and many more.
High performance: Java provides high performance with the help of features like JVM,
interpretation, and its simplicity.
Distributed: Java programming language supports TCP/IP protocols which enable the
java to support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods across a
network.
Dynamic: Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and de-allocation
(objects and garbage collector).
An Overview of Java:
Java is a computer programming language. Java was created based on C and C++. Java
uses C syntax and many of the object-oriented features are taken from C++. Before Java
was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk,
etc. These languages had few disadvantages which were corrected in Java. Java also has
many new features to solve the fundamental problems which the previous languages
could not solve. Java was invented by a team of 13 employees of Sun Microsystems, Inc.
which is lead by James Gosling, in 1991. The team includes persons like Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as a
part of the Green project. Initially, it was called Oak, later it was changed to Java in
1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become
the most popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with
included OOP fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was to create
a programming tool that could render obsolete the C and C++ programming
languages.
Finally in the year of 1991 the Green Team was created a new Programming language
named “OAK”.
After some time they found that there is already a programming language with the
name “OAK”.
So, the green team had a meeting to choose a new name. After so many discussions
they want to have a coffee. They went to a Coffee Shop which is just outside of the
Gosling’s office and there they have decided name as “JAVA”.
The primitive data types are built-in data types and they specify the type of value stored
in a variable and the memory size. The primitive data types do not have any additional
methods.
In java, primitive data types includes byte, short, int, long, float, double, char,
and boolean.
The following table provides more description of each primitive data type.
Let's look at the following example java program to illustrate primitive data types in java
and their default values.
Example
public class PrimitiveDataTypes
{
byte i; short j; int k; long l; float m; double n;
char ch; boolean p;
public static void main(String[] args)
{
PrimitiveDataTypes obj = new PrimitiveDataTypes();
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}
In java, non-primitive data types are the reference data types or user-created data types.
All non-primitive data types are implemented using object concepts. Every variable of the
non-primitive data type is an object. The non-primitive data types may use additional
methods to perform certain operations. The default value of non-primitive data type
variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack,
Class, Interface, etc.
Example:
public class NonPrimitiveDataTypes
{
String str;
public static void main(String[] args)
{
String name = "BTech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str); //using addition method
System.out.println(wish.concat(name));
}
}
These are built-in data types These are created by the users
Java Variables: A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.
In java, we use the following syntax to create variables.
Syntax:
data_type variable_name; (or)
data_type variable_name_1; (or)
data_type variable_name = value; (or)
data_type variable_name_1 = value;
1. Local variables: The variables declared inside a method or a block are known as local
variables. A local variable is visible within the method in which it is declared. The
local variable is created when execution control enters into the method or block and
destroyed after the method or block execution completed.
Example:
public class LocalVariables
{
public void show()
{
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
System.out.println("Inside display method, a = " + a);
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
Example
public class ClassVariables
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args)
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
Example
public class StaticVariablesExample
{
int x, y; // Instance variables
static int z; // Static variable
StaticVariablesExample(int x, int y)
{
this.x = x;
this.y = y;
}
public void show()
{
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args)
{
StaticVariablesExample obj_1 = new StaticVariablesExample(10, 20);
StaticVariablesExample obj_2 = new StaticVariablesExample(100, 200);
obj_1.show();
StaticVariablesExample.z = 1000;
obj_2.show();
}
}
4. Final variables
A final variable is a variable that declared using final keyword. The final variable is
initialized only once, and does not allow any method to change it's value again. The
variable created using final keyword acts as constant. All variables like local,
instance, and static variables can be final variables.
Example
public class FinalVariableExample
{
final int a = 10;
void show()
{
System.out.println("a = " + a);
a = 20; //Error due to final variable cann't be modified
}
public static void main(String[] args)
{
FinalVariableExample obj = new FinalVariableExample();
obj.show();
}
}
Java Arrays: An array is a collection of similar data values with a single name. An
array can also be defined as, a special type of variable that holds multiple values of the
same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every
array in java is organized using index values. The index value of an array starts with '0'
and ends with 'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
Creating an array: In the java programming language, an array must be created using
new operator and with a specific size. The size must be an integer value but not a byte,
short, or long. We use the following syntax to create an array.
Syntax
data_type array_name[ ] = new data_type[size]; (or)
data_type[ ] array_name = new data_type[size];
Example
public class ArrayExample
{
public static void main(String[] args)
{
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
In java, an array can also be initialized at the time of its declaration. When an array is
initialized at the time of its declaration, it need not specify the size of the array and use
of the new operator. Here, the size is automatically decided based on the number of
values that are initialized.
NullPointerException with Arrays: In java, an array created without size and initialized
to null remains null only. It does not allow us to assign a value. When we try to assign a
value it generates a NullPointerException.
Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = null;
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
Looping through an array: An entire array is accessed using either simple for
statement or for-each statement. Look at the following example program to display sum
of all the elements in a list.
Example
import java.util.Scanner;
public class ArrayExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int size, sum = 0;
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and
columns. The individual element is accessed using the respective row index followed by
the column index. A multidimensional array can be initialized while it has created using
the following syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};
When an array is initialized at the time of declaration, it need not specify the size of the
array and use of the new operator. Here, the size is automatically decided based on the
number of values that are initialized.
The above statement creates a two-dimensional array of three rows and two columns.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides
a rich set of operators.
In java, operators are classified into the following four types.
1. Arithmetic Operators
2. Relational (or) Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Conditional Operators
Let's look at each operator in detail.
1. Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like
addition, subtraction, multiplication, division, modulus, increment, decrement, etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
< Returns TRUE if the first value is smaller than 10 < 5 is FALSE
second value otherwise returns FALSE
> Returns TRUE if the first value is larger than 10 > 5 is TRUE
second value otherwise returns FALSE
<= Returns TRUE if the first value is smaller than 10 <= 5 is FALSE
or equal to second value otherwise returns
FALSE
>= Returns TRUE if the first value is larger than or 10 >= 5 is TRUE
equal to second value otherwise returns FALSE
3. Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into
one condition. The following table provides information about logical operators.
Operator Meaning Example
& Logical AND - Returns TRUE if all conditions are false & true => false
TRUE otherwise returns FALSE
| Logical OR - Returns FALSE if all conditions are false | true => true
FALSE otherwise returns TRUE
^ Logical XOR - Returns FALSE if all conditions are true ^ true => false
same otherwise returns TRUE
&& short-circuit AND - Similar to Logical AND (&), but false & true => false
once a decision is finalized it does not evaluate
remaining.
4. Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-
hand side variable (Lvalue). The assignment operator is used in different variants along
with arithmetic operators. The following table describes all the assignment operators in
the java programming language.
+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable
side variable
|= Logical OR assignment -
5. Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on
binary values.
The following table describes all the bitwise operators in the java programming language.
6. Conditional Operators
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the condition is
FALSE the second option is performed. The conditional operator is used with the
following syntax.
Syntax: Condition ? TRUE Part : FALSE Part;
Example
public class ConditionalOperator
{
public static void main(String[] args)
{
int a = 10, b = 20, c;
c = (a>b)? a : b;
System.out.println("c = " + c);
}
}
Operands are the values on which the operators perform the task. Here operand can be
a direct value or variable or address of memory location.
Expression Types: In the java programming language, expressions are divided into
THREE types. They are as follows.
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
Infix Expression- The expression in which the operator is used between operands is
called infix expression. The infix expression has the following general structure.
Example
Postfix Expression: The expression in which the operator is used after operands is
called postfix expression. The postfix expression has the following general structure.
Example
Prefix Expression: The expression in which the operator is used before operands is
called a prefix expression. The prefix expression has the following general structure.
Example
In java, the control statements are the statements which will tell us that in which order
the instructions are getting executed. The control statements are used to control the
order of execution according to our requirements. Java provides several control
statements, and they are classified as follows.
Types of Control Statements: In java, the control statements are classified as follows.
Selection Control Statements ( Decision Making Statements )
Iterative Control Statements ( Looping Statements )
Jump Statements
while statement
do-while statement
for statement
for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control
to the next iteration. Java provides the following jump statements.
break
continue
return
if statement in java
In java, we use if statement to test a condition and decide the execution of a block of
statements based on that condition result. if statement checks, the given condition then
decides the execution of a block of statements. If the condition is true, then the block of
statements is executed and if it is False, then the block of statements is ignored. The
syntax and execution flow of if the statement is as follows.
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
}
}
Syntax
if(condition_1)
{
condition_1 true-block;
}
else if(condition_2)
{
condition_2 true-block;
condition_1 false-block too;
}
Example:
while(num <= 10)
{
System.out.println(num);
num++;
}
for statement in java: The for statement is used to execute a single statement or a
block of statements repeatedly as long as the given condition is TRUE.
Example:
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
for-each statement in java: The Java for-each statement was introduced since Java 5.0
version. It provides an approach to traverse through an array or collection in Java. The
for-each statement also known as enhanced for statement. The for-each statement
executes the block of statements for each element of the given array or collection.
Example:
for(int i : arrayList)
{
System.out.println("i = " + i);
}
break statement: The break statement in java is used to terminate a switch or looping
statement. That means the break statement is used to come out of a switch statement
and a looping statement like while, do-while, for, and for-each.
continue statement: The continue statement is used to move the execution control to
the beginning of the looping statement. When the continue statement is encountered in a
looping statement, the execution control skips the rest of the statements in the looping
block and directly jumps to the beginning of the loop. The continue statement can be
used with looping statements like while, do-while, for, and for-each.
labeled break and continue statements: The java programming language does not
support goto statement, alternatively, the break and continue statements can be used
with label.
return statement: In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling function.
That means the return statement transfer the execution control from called function to
the calling function by carrying a value.
Java Classes:
Java is an object-oriented programming language, so everything in java program must be
based on the object concept. In a java programming language, the class concept defines
the skeleton of an object.
The java class is a template of an object. The class defines the blueprint of an object.
Every class in java forms a new data type. Once a class got created, we can generate as
many objects as we want. Every class defines the properties and behaviors of an object.
All the objects of a class have the same properties and behaviors that were defined in the
class.
Look at the following picture to understand the class and object concept.
Creating a Class: In java, we use the keyword class to create a class. A class in java
contains properties as variables and behaviors as methods. Following is the syntax of
class in the java.
Syntax
class <ClassName>
{
data members declaration;
methods defination;
}
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class
is said to be instantiated. All the objects that are created using a single class have the
same properties and methods. But the value of properties is different for every object.
Following is the syntax of class in the java.
Java Methods:
A method is a block of statements under a name that gets executes only when it is
called. Every method is used to perform a specific task. The major advantage of methods
is code re-usability (define the code once, and use it many times).
Creating a method: A method is created inside the class and it may be created with any
access specifier. However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>
{
<accessSpecifier> <returnType> <methodName>( parameters )
{
block of statements;
}
}
Calling a method: In java, a method call precedes with the object name of the class to
which it belongs and a dot operator. It may call directly if the method defined with the
static modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.
Constructor: A constructor is a special method of a class that has the same name as the
class name. The constructor gets executes automatically on object creation. It does not
require the explicit method call. A constructor may have parameters and access specifies
too. In java, if you do not provide any constructor the compiler automatically creates a
default constructor.
Example
public class ConstructorExample
{
ConstructorExample()
{
System.out.println("Object created!");
}
public static void main(String[] args)
{
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}
The string created using a character array can not be extended. It does not allow to
append more characters after its definition, but it can be modified.
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);
The string created using the String class can be extended. It allows us to add more
characters after its definition, and also it can be modified.
Example
String siteName = "JavaProgram.com";
siteName = "JavaProgram.com";
Inheritance:
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in
another class. The inheritance provides a greate advantage called code re-usability. With
the help of code re-usability, the commonly used code in an application need not be
written again and again.
Types of Inheritance: When deriving a class from a base class, the base class may be
inherited through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above. We hardly use protected or private
inheritance, but public inheritance is commonly used. While using different type of
inheritance, following rules are applied:
Creating Child Class in java: In java, we use the keyword extends to create a child
class. The following syntax used to create a child class in java.
Syntax
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}
In a java programming language, a class extends only one class. Extending multiple
classes is not allowed in java.
Example:
class ParentClass
{
int a;
void setData(int a)
{
this.a = a;
}
}
class ChildClass extends ParentClass
{
void showData()
{
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.setData(100);
obj.showData();
}
}
Java Access Modifiers: In Java, the access specifiers (also known as access modifiers)
used to restrict the scope or accessibility of a class, constructor, variable, method or
data member of class and interface. There are four access specifiers, and their list is
below.
Let's look at the following example java code, which generates an error because a class
does not allow private access specifier unless it is an inner class.
Example
private class Sample
{
}
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.
Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
In java, the default constructor of a parent class called automatically by the constructor
of its child class. That means when we create an object of the child class, the parent
class constructor executed, followed by the child class constructor executed.
Example1
class ParentClass
{
int a;
ParentClass()
{
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("Inside ChildClass constructor!!");
}
}
However, if the parent class contains both default and parameterized constructor, then
only the default constructor called automatically by the child class constructor.
Example2
class ParentClass
{
int a;
ParentClass(int a)
{
System.out.println("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass()
{
System.out.println("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
}
}
The parameterized constructor of parent class must be called explicitly using the super
keyword.
Super keyword: In java, super is a keyword used to refer to the parent class object. The
super keyword came into existence to solve the naming conflicts in the inheritance.
When both parent class and child class have members with the same name, then the
super keyword is used to refer to the parent class version.
super to refer parent class data members: When both parent class and child class
have data members with the same name, then the super keyword is used to refer to the
parent class data member from child class.
To call the parameterized constructor of the parent class, the super keyword must be the
first statement inside the child class constructor, and we must pass the parameter
values.
super to refer parent class method: When both parent class and child class have
method with the same name, then the super keyword is used to refer to the parent class
method from child class.
super to call parent class constructor: When an object of child class is created, it
automatically calls the parent class default-constructor before its own. But, the
parameterized constructor of parent class must be called explicitly using the super
keyword inside the child class constructor.
To call the parameterized constructor of the parent class, the super keyword must be the
first statement inside the child class constructor, and we must pass the parameter
values.
Final keyword: In java, the final is a keyword and it is used with the following things.
With variable (to create constant)
With method (to avoid method overriding)
With class (to avoid inheritance)
Final with variables: When a variable defined with the final keyword, it becomes a
constant, and it does not allow us to modify the value. The variable defined with the final
keyword allows only a one-time assignment, once a value assigned to it, never allows us
to change it again.
Final with methods: When a method defined with the final keyword, it does not allow it
to override. The final method extends to the child class, but the child class cannot
override or re-define it. It must be used as it has implemented in the parent class.
Final with class: When a class defined with final keyword, it cannot be extended by any
other class.
Polymorphism:
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behavior.
In java, polymorphism implemented using method overloading and method overriding.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism.
Every function call binded with the respective overloaded method based on the
arguments.
Pure polymorphism: The pure polymorphism is a technique used to define the same
method with the same arguments but different implementations. In a java programming
language, pure polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Example
class ParentClass
{
int num = 10;
void showData()
{
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
The method overriding enables the child class to change the implementation of the
method which acquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The
method binding which happens at run time is known as late binding. So, the method
overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Syntax
abstract class <ClassName>
{
}
An abstract class cannot be instantiated but can be referenced. That means we cannot
create an object of an abstract class, but base reference can be created.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't
know. Because it is the super class of all other classes in java, it can refer to any type of
object.
Return
Method Description Value
hashCode() returns the hashcode number for object being used. int
wait(long,int) causes the current thread to wait for the specified void
milliseconds and nanoseconds, until another thread
notifies.
class may be substituted with the child class object. For example, if B is a child class of
A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
Specialization: It is the most ideal form of inheritance. The subclass is a special case of
the parent class. It holds the principle of substitutability.
Construction: This is another form of inheritance where the child class may change the
behavior defined by the parent class (overriding). It does not hold the principle of
substitutability.
Extension: This is another form of inheritance where the child class may add its new
properties. It holds the principle of substitutability.
Limitation: This is another form of inheritance where the subclass restricts the
inherited behavior. It does not hold the principle of substitutability.
Combination: This is another form of inheritance where the subclass inherits properties
from multiple parent classes. Java does not support multiple inheritance type.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.