0% found this document useful (0 votes)
2 views37 pages

Java Unit I Part II

This document is a course outline for a II B.Tech II-Semester Java Programming class, covering key concepts of object-oriented programming including classes, inheritance, methods, and string handling in Java. It details the rules for creating classes and methods, the process of object creation, and provides examples of constructors and string manipulation. The document serves as a comprehensive guide for students to understand Java programming fundamentals and its applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Java Unit I Part II

This document is a course outline for a II B.Tech II-Semester Java Programming class, covering key concepts of object-oriented programming including classes, inheritance, methods, and string handling in Java. It details the rules for creating classes and methods, the process of object creation, and provides examples of constructors and string manipulation. The document serves as a comprehensive guide for students to understand Java programming fundamentals and its applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

KARMNAGAR -

505481

II [Link] II- Semester Java Programming (R18) 2021-22


II [Link] II- Semester


CS405PC
Java Programming (R18) 2021-22

UNIT-I PART-II

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 1


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


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

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.

Every class of java programming language has the following characteristics.

Identity - It is the name given to the class.


State - Represents data values that are associated with an object.
Behavior - Represents actions can be performed by an object.
Look at the following picture to understand the class and object concept.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 2


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Rules to Create a Class


1. A Java class must have the class keyword followed by the class name, and class
must be followed by a legal identifier.
2. The class name must start with a capital letter and if you are using more than one
word to define a class name, every first letter of the latter words should be made
capital.
3. There should not be any spaces or special characters used in a class name except the
dollar symbol($) and underscore(_).
4. A Java class can only have public or default access specifier.
5. It must have the class keyword, and class must be followed by a legal identifier.
6. It can extend only one parent class. By default, all the classes extend
[Link] directly or indirectly.
7. A class may optionally implement any number of interfaces separated by commas.
8. The class’s members must be always declared within a set of curly braces {}.
9. Each .java source file can contain any number of default classes but can only have
one public class.
10. Class containing the main() method is known as the Main class as it will act as the
entry point to your program.

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

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 3


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22



​How to Create a Java Object?
There are three simple steps to create Java objects which are listed below:

● Declaration − this is the very first step of object creation. In this step, you need to
declare a variable with the class name as the data type.
● Instantiation − Next step is the instantiation where you need to use the ‘new’
keyword to create the object.
● Initialization − finally in the third step, you need to initialize the object by calling the
class constructor.

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.

Syntax
<ClassName> <objectName> = new <ClassName>( );

Example:
public class CseDemo{
public CseDemo() {
// Default Constructor
[Link]("This is a default constructor");
}
public CseDemo(String name) {
// This constructor has one parameter
[Link]("Hello: " + name );
[Link]("Welcome to II CSE Java Programming");
}

public static void main(String []args) {


//Creating an object using default constructor
CseDemo myObj = new CseDemo();

//Creating an object using parameterized constructor


CseDemo myObj1 = new CseDemo( "Varunjoel" );
}
}
Output:
This is a default constructor
Hello: Varunjoel

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 4


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Welcome to II CSE Java Programming

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

In a java programming language, a method defined as a behavior of an object. That means,


every method in java must belong to a class.

Every method in java must be declared inside a class.

Every method declaration has the following characteristics.

✔ returnType - Specifies the data type of a return value.


✔ name - Specifies a unique name to identify it.
✔ parameters - The data values it may accept or recieve.
✔ { } - Defienes the block belongs to the method.

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

❖ The methodName must begin with an alphabet, and the Lower-case letter is preferred.
❖ The methodName must follow all naming rules.
❖ If you don't want to pass parameters, we ignore it.
❖ If a method defined with return type other than void, it must contain the return
statement; otherwise, it may be ignored.

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

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 5


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


with a semicolon.

Syntax
<objectName>.<methodName>( actualArguments );

❖ The method call must pass the values to parameters if it has.


❖ If the method has a return type, we must provide the receiver.

Example:
import [Link];
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner([Link]);

void readData() {
[Link]("Enter Serial Number: ");
sNo = [Link]();
[Link]("Enter the Name: ");
name = [Link]();
}

static void showData(int sNo, String name) {


[Link]("Hello, " + name + "! your serial number is " + sNo);
}

public static void main(String[] args) {


JavaMethodsExample obj = new JavaMethodsExample();
[Link](); // method call using object
showData([Link], [Link]); // method call without using object
}
}
Output:
Enter Serial Number: 777
Enter the Name: varunjoel
Hello, varunjoel! your serial number is 777

Note:
❖ The objectName must begin with an alphabet, and a Lower-case letter is preferred.
❖ The objectName must follow all naming rules.

Variable arguments of a method


In java, a method can be defined with a variable number of arguments. That means creating
a method that receives any number of arguments of the same data type.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 6
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Syntax
<returnType> <methodName>(dataType...parameterName);

Example:
public class JavaMethodWithVariableArgs {
void diaplay(int...list) {
[Link]("\nNumber of arguments: " + [Link]);
for(int i : list) {
[Link](i + "\t");
}
}

public static void main(String[] args) {


JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();
[Link](1, 2);
[Link](10, 20, 30, 40, 50);
}
}
Output:
Number of arguments: 2
1 2
Number of arguments: 5
10 20 30 40 50

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 specifiers too. In java, if you do
not provide any constructor the compiler automatically creates a default constructor.

Example:
public class ConstructorExample {

ConstructorExample() {
[Link]("Object created!");
}
public static void main(String[] args) {
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}
Output:
Object created!
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 7
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Object created!

Note: A constructor cannot have return value.

Java String Handling


A string is a sequence of characters surrounded by double quotations. In a java
programming language, a string is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.

The string created using a character array cannot be extended. It does not allow appending
more characters after its definition, but it can be modified.

Example
char[] name = {'v', 'a', 'r', 'u', 'n', ' ', 'j', 'o', 'e', 'l'};
//name[10] = '@'; //ArrayIndexOutOfBoundsException
name[6] = '-';
[Link] (name);

The String class defined in the package [Link] package. The String class implements
Serializable, Comparable, and Char Sequence interfaces.

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 = "[Link]";
siteName = "[Link]

Creating String object in java


In java, we can use the following two ways to create a string object.

✔ Using string literal


✔ Using String constructor

Example
String title = "Java Programming"; // Using literals
String siteName = new String("[Link]"); // Using constructor

Note:
The String class constructor accepts both string and character array as an argument.

String handling methods


Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 8
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


In java programming language, the String class contains various methods that can be used to
handle string data values. It containg methods like concat( ), compareTo( ), split( ), join( ),
replace( ), trim( ), length( ), intern( ), equals( ), comparison( ), substring( ), etc.

The following table depicts all built-in methods of String class in java.
Return
Method Description
Value
charAt(int) Finds the character at given index char
length() Finds the length of given string int
compareTo(String) Compares two strings int
compareToIgnoreCase(String) Compares two strings, ignoring case int
Concatenates the object string with argument
concat(String) String
string.
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
Checks whether two strings are same, ignoring
equalsIgnoreCase(String) boolean
case
Checks whether a string starts with the
startsWith(String) boolean
specified string
Checks whether a string ends with the
endsWith(String) boolean
specified string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
Finds the first index of argument string in
indexOf(String) int
object string
Finds the last index of argument string in
lastIndexOf(String) int
object string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
Replaces the first string with second string at
replaceAll(String, String) String
all occurrences.
Extracts a sub-string from specified start and
substring(int, int) String
end index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String

Example:
public class JavaStringExample
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 9
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


{
public static void main(String[] args)
{
String title = "Jyothishmathi Karimnagar";
String siteName = "[Link]";

[Link] ("Length of title: " + [Link]());


[Link] ("Char at index 3: " + [Link](3));
[Link] ("Index of 'K': " + [Link]('K'));
[Link] ("Last index of 'a': " + [Link]('a'));
[Link] ("Empty: " + [Link]());
[Link] ("Ends with '.com': " + [Link](".com"));
[Link] ("Equals: " + [Link](title));
[Link] ("Sub-string: " + [Link](9, 14));
[Link] ("Upper case: " + [Link]());
}
}
Output:
Length of title: 24
Char at index 3: t
Index of 'K': 14
Last index of 'a': 22
Empty: false
Ends with '.com': false
Equals: false
Sub-string: [Link]
Upper case: [Link]

Java Inheritance Basics

Inheritance Concept
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 great 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.
“The inheritance is the process of acquiring the properties of one class to another class.”

Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 10


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


The Parent class is the class which provides features to another class. The parent class is
also known as Base class or Superclass.

The Child class is the class which receives features from another class. The child class is
also known as the Derived Class or Subclass.

Note:
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.

There are five types of inheritances, and they are as follows.

✔ Simple Inheritance (or) Single Inheritance

✔ Multiple Inheritance

✔ Multi-Level Inheritance

✔ Hierarchical Inheritance

✔ Hybrid Inheritance
The following picture illustrates how various inheritances are implemented.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 11


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Note:
The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.

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

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 12


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Note:
In a java programming language, a class extends only one class. Extending multiple classes
is not allowed in java.

Single Inheritance in java
In this type of inheritance, one child class derives from one parent class.
Example:
class ParentClass
{
int a;
void setData(int a)
{
this.a = a;
}
}
class ChildClass extends ParentClass
{
void showData()
{
[Link]("Value of a is " + a);
}
}
public class SingleInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


[Link](100);
[Link]();
}
}
Output:
Value of a is 100

Multi-level Inheritance in java


In this type of inheritance, the child class derives from a class which already derived from
another class.
Example:
class ParentClass{
int a;
void setData(int a) {
this.a = a;

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 13


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
[Link]("Inside ChildChildClass!");
}
}
public class MultipleInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


[Link](100);
[Link]();
[Link]();
}
}
Output:
Value of a is 100
Inside ChildChildClass!

Hierarchical Inheritance in java


In this type of inheritance, two or more child classes derive from one parent class.

Example:
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass!");
[Link]("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 14
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


void display() {
[Link]("Inside ChildClassToo!");
[Link]("Value of a is " + a);
}
}
public class HierarchicalInheritance {

public static void main(String[] args) {

ChildClass child_obj = new ChildClass();


child_obj.setData(100);
child_obj.showData();

ChildClassToo childToo_obj = new ChildClassToo();


childToo_obj.setData(200);
childToo_obj.display();
}
}
Output:
Inside ChildClass!
Value of a is 100
Inside ChildClassToo!
Value of a is 200

Hybrid Inheritance in java


The hybrid inheritance is the combination of more than one type of inheritance. We may use
any combination as a single with multiple inheritances, multi-level with multiple
inheritances, etc.,

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.

✔ default (or) no modifier


✔ public
✔ protected
✔ private
In java, we cannot employ all access specifiers on everything. The following table describes
where we can apply the access specifiers.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 15


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

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.

✔ The public members can be accessed everywhere.


✔ The private members can be accessed only inside the same class.
✔ The protected members are accessible to every child class (same package or other
packages).
✔ The default members are accessible within the same package but not outside the
package.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 16


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Example:
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
[Link]("Inside ParentClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}

class ChildClass extends ParentClass{

void accessData() {
[Link]("Inside ChildClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
//[Link]("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
[Link]();
[Link]();
}
}
Output:
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 17


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


c = 30

Java Constructors in Inheritance

A constructor in Java is a special method that is used to initialize objects.

​The constructor is called when an object of a class is created. It can be used to


set initial values for object attributes.

​How Constructors are Different From Methods in Java?

● Constructors must have the same name as the class within which it is defined
while it is not necessary for the method in Java.
● Constructors do not return any type while method(s) have the return type
or void if does not return any value.
● Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.

Example:
class ParentClass{
int a;
ParentClass() {
[Link]("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{

ChildChildClass(){
[Link]("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


}
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 18
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


}
Output:
Inside ParentClass constructor!
Inside ChildClass constructor!!
Inside ChildChildClass constructor!!

However, if the parent class contains both default and parameterized constructor, then only
the default constructor called automatically by the child class constructor.

Example:
class ParentClass{
int a;
ParentClass(int a){
[Link]("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
[Link]("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


}
}
Output:
Inside ParentClass default constructor!
Inside ChildClass constructor!!

Note:
The parameterized constructor of parent class must be called explicitly using the super
keyword.

Java super keyword


In java, super is a keyword used to refer to the parent class object. The super keyword came
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 19
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


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.

In java, the super keyword is used for the following purposes.

✔ To refer parent class data members


✔ To refer parent class methods
✔ To call parent class constructor

Note:
The super keyword is used inside the child class only.
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.

Example:
class ParentClass{
int num = 10;
}

class ChildClass extends ParentClass{


int num = 20;

void showData() {
[Link]("Inside the ChildClass");
[Link]("ChildClass num = " + num);
[Link]("ParentClass num = " + [Link]);
}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

[Link]();

[Link]("\nInside the non-child class");


[Link]("ChildClass num = " + [Link]);
//[Link]("ParentClass num = " + [Link]); //super can't be used here
}
}
Output:

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 20


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Inside the ChildClass
ChildClass num = 20
ParentClass num = 10

Inside the non-child class


ChildClass num = 20

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.
Example:
class ParentClass{
int num1 = 10;

void showData() {
[Link]("\nInside the ParentClass showData method");
[Link]("ChildClass num = " + num1);
}
}

class ChildClass extends ParentClass{

int num2 = 20;

void showData() {
[Link]("\nInside the ChildClass showData method");
[Link]("ChildClass num = " + num2);

[Link]();
}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

[Link]();
//[Link](); // super can't be used here
}
}
Output:
Inside the ChildClass showData method
ChildClass num = 20

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 21


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Inside the ParentClass showData method


ChildClass num = 10

super to call parent class constructor


When an object of child class is created, it automatically calls the parent class
default-constructor before it's own. But, the parameterized constructor of parent class must
be called explicitly using the super keyword inside the child class constructor.

Example:
class ParentClass{

int num1;

ParentClass(){
[Link]("\nInside the ParentClass default constructor");
num1 = 10;
}

ParentClass(int value){
[Link]("\nInside the ParentClass parameterized constructor");
num1 = value;
}
}

class ChildClass extends ParentClass{

int num2;

ChildClass(){
super(100);
[Link]("\nInside the ChildClass constructor");
num2 = 200;
}
}

public class SuperKeywordExample {


public static void main(String[] args) {

ChildClass obj = new ChildClass();


}
}
Output:
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 22
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Inside the ParentClass parameterized constructor

Inside the ChildClass constructor

Note:
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.

Java 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.
Example:
public class FinalVariableExample {
public static void main(String[] args) {

final int a = 10;

[Link]("a = " + a);

//a = 100; // Can't be modified


}
}
Output:
a = 10

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 can not override or re-define it. It must
be used as it has implemented in the parent class.

Example:
class ParentClass{

int num = 10;

final void showData() {


Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 23
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}

class ChildClass extends ParentClass{

void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}

public class FinalKeywordExample {


public static void main(String[] args) {

ChildClass obj = new ChildClass();


[Link]();
}
}
Output:
/[Link]: error: showData() in ChildClass cannot override
showData() in ParentClass
void showData() {
^
overridden method is final
1 error

final with class


When a class defined with final keyword, it can not be extended by any other class.

Example:
final class ParentClass{
int num = 10;

void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}

class ChildClass extends ParentClass{

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 24


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

public class FinalKeywordExample {


public static void main(String[] args) {

ChildClass obj = new ChildClass();


}
}
Output:
[Link]: error: cannot inherit from final ParentClass
class ChildClass extends ParentClass{
^
1 error

Java Polymorphism
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.

In java, polymorphism implemented using method overloading and method overriding.


Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.

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.

Note:
The ad hoc polymorphism implemented within the class only.

Example:
import [Link];

public class AdHocPolymorphismExample {

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 25


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


void sorting(int[] list) {
[Link](list);
[Link]("Integers after sort: " + [Link](list) );
}
void sorting(String[] names) {
[Link](names);
[Link]("Names after sort: " + [Link](names) );
}
public static void main(String[] args) {

AdHocPolymorphismExample obj = new AdHocPolymorphismExample();


int list[] = {2, 3, 1, 5, 4};
[Link](list); // Calling with integer array

String[] names = {"rama", "raja", "shyam", "seeta"};


[Link](names); // Calling with String array
}
}
Output:
Integers after sort: [1, 2, 3, 4, 5]
Names after sort: [raja, rama, seeta, shyam]

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() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 26


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


}
}

class ChildClass extends ParentClass{

void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


[Link]();

obj = new ChildClass();


[Link]();
}
}
Output:
Inside ParentClass showData() method
num = 10
Inside ChildClass showData() method
num = 10
Java Method Overriding
The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.
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.
Example:
class ParentClass{

int num = 10;


Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 27
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}
class ChildClass extends ParentClass{

void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


[Link]();

obj = new ChildClass();


[Link]();
}
}
Output:
Inside ParentClass showData() method
num = 10
Inside ChildClass showData() method
num = 10
10 Rules for method overriding
While overriding a method, we must follow the below list of rules.

✔ Static methods cannot be overridden.


✔ Final methods cannot be overridden.
✔ Private methods cannot be overridden.
✔ Constructor cannot be overridden.
✔ An abstract method must be overridden.
✔ Use super keyword to invoke overridden method from child class.
✔ The return type of the overriding method must be same as the parent has it.
✔ The access specifier of the overriding method can be changed, but the visibility must
increase but not decrease. For example, a protected method in the parent class can be
made public, but not private, in the child class.
✔ If the overridden method does not throw an exception in the parent class, then the
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 28
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


child class overriding method can only throw the unchecked exception, throwing a
checked exception is not allowed.
✔ If the parent class overridden method does throw an exception, then the child class
overriding method can only throw the same, or subclass exception, or it may not
throw any exception.

Java Abstract Class


An abstract class is a class that created using abstract keyword. In other words, a class
prefixed with abstract keyword is known as an abstract class.

In java, an abstract class may contain abstract methods (methods without implementation)
and also non-abstract methods (methods with implementation).

We use the following syntax to create an abstract class.


Syntax
abstract class <ClassName>{
...
}

Example:
import [Link].*;

abstract class Shape {


int length, breadth, radius;
Scanner input = new Scanner([Link]);

abstract void printArea();


}

class Rectangle extends Shape {


void printArea() {
[Link]("*** Finding the Area of Rectangle ***");
[Link]("Enter length and breadth: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
[Link]("\n*** Finding the Area of Triangle ***");
[Link]("Enter Base And Height: ");
length = [Link]();

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 29


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


breadth = [Link]();
[Link]("The area of Triangle is: " + (length * breadth) / 2);
}
}

class Cricle extends Shape {


void printArea() {
[Link]("\n*** Finding the Area of Cricle ***");
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("The area of Cricle is: " + 3.14f * radius * radius);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Rectangle rec = new Rectangle();
[Link]();

Triangle tri = new Triangle();


[Link]();

Cricle cri = new Cricle();


[Link]();
}
}
Output:
*** Finding the Area of Rectangle ***
Enter length and breadth: The area of Rectangle is: 8

*** Finding the Area of Triangle ***


Enter Base And Height: The area of Triangle is: 12

*** Finding the Area of Cricle ***


Enter Radius: The area of Cricle is: 153.86002

Note:
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.

In the above example program, the child class objects are created to invoke the overridden
abstract method. But we may also create base class reference and assign it with child class
instance to invoke the same. The main method of the above program can be written as
follows that produce the same output.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 30


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Example
public static void main(String[] args) {
Shape obj = new Rectangle(); //Base class reference to Child class instance
[Link]();

obj = new Triangle();


[Link]();

obj = new Cricle();


[Link]();
}

8 Rules for method overriding


An abstract class must follow the below list of rules.

● An abstract class must be created with abstract keyword.


● An abstract class can be created without any abstract method.
● An abstract class may contain abstract methods and non-abstract methods.
● An abstract class may contain final methods that cannot be overridden.
● An abstract class may contain static methods, but the abstract method cannot be
static.
● An abstract class may have a constructor that gets executed when the child class
object created.
● An abstract method must be overridden by the child class, otherwise, it must be
defined as an abstract class.
● An abstract class cannot be instantiated but can be referenced.

Java Object Class


In java, the Object class is the super most class of any class hierarchy. The Object class in
the java programming language is present inside the [Link] package.

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 superclass of all other classes in java, it can refer to any type of object.

Methods of Object class


The following table depicts all built-in methods of Object class in java.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 31


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


Method Description Return
Value
getClass() Returns Class class object object
hashCode() returns the hashcode number for object being used. int
equals(Object obj) compares the argument object to calling object. boolean
clone() Compares two strings, ignoring case int
concat(String) Creates copy of invoking object object
toString() eturns the string representation of invoking object. String
notify() wakes up a thread, waiting on invoking object's monitor. void
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.
finalize() It is invoked by the garbage collector before an object is being void
garbage collected.

Java Forms of Inheritance

The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability. The substitutability means that when a child
class acquires properties from its parent class, the object of the parent 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.

The following are the different forms of inheritance in java.

● Specialization
● Specification
● Construction
● Extension
● Limitation
● Combination
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.

Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't
implement them. The java provides concepts like abstract and interfaces to support this form

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 32


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


of inheritance. 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 and Costs of Inheritance in java


The inheritance is the core and more useful concept Object Oriented Programming. 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. It provides lot of benefits and
few of them are listed below.

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.

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 33


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


● The overuse of inheritance makes the program more complex.

BufferedReader class

The BufferedReader class of Java is used to read the stream of characters from the specified
source (character-input stream). The constructor of this class accepts an InputStream object
as a parameter.
This class provides a method known as readLine() which reads and returns the next line
from the source and returns it in String format.
The BufferedReader class doesn’t provide any direct method to read an integer from the
user you need to rely on the readLine() method to read integers too. i.e. Initially you need to
read the integers in string format.
The parseInt() method of the Integer class accepts a String value, parses it as a signed
decimal integer and returns it.
Using this convert the read Sting value into integer and use. In short, to read integer
value-form user using BufferedReader class −
● Instantiate an InputStreamReader class bypassing your InputStream object as a
parameter.
● Then, create a BufferedReader, bypassing the above obtained InputStreamReader
object as a parameter.
● Now, read integer value from the current reader as String using
the readLine() method.
● Then parse the read String into an integer using the parseInt() method of the Integer
class.
Example:1
The following Java program demonstrates how to read integer data from the user using
the BufferedReader class.
import [Link];
import [Link];
import [Link];
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
[Link] = name;
[Link] = age;
[Link] = id;
}
public void displayDetails(){
[Link]("Name: "+[Link]);
[Link]("Age: "+[Link]);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 34
KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


[Link]("Id: "+[Link]);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]([Link]());
[Link]("Enter your Id: ");
int id = [Link]([Link]());
Employee std = new Employee(name, age, id);
[Link]();
}
}
Output:
Enter your name: Varunjoel
Enter your age: 40
Enter your Id:777
Name: Varunjoel
Age: 40
Id: 777

Example:2
//import [Link];
//import [Link];
//import [Link];
import [Link].*;

public class Test


{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader reader= new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter Your Name");


// Reading data using readLine
String name = [Link]();

// Printing the read line


[Link](name);

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 35


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22


}
}
Output:
Enter your name: Jyothishmathi
Jyothishmathi

Java Console Class


The Java Console class is be used to get input from console. It provides methods to read
texts and passwords.

If you read password using Console class, it will not be displayed to the user.

The [Link] class is attached with system console internally. The Console class is
introduced since 1.5.

simple example to read text from console.


String text=[Link]().readLine();
[Link]("Text is: "+text);

Example:
//Write a java program to demonstrate the console class.
import [Link].*;
class Ex_Console
{
public static void main(String[] args)
{
Console kb=[Link]();
[Link]("Enter ur name:");
String name=[Link]();
[Link]("enter your address:");
String addr=[Link]();
[Link]("Your details are:");
[Link]("Name: "+name);
[Link]("Address: "+addr);

}
}
Output:
Enter ur name: venkywn
Enter your address: karimnagar
Your details are:
Name: venkywn
Address: karimnagar

Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 36


KARMNAGAR -
505481

II [Link] II- Semester Java Programming (R18) 2021-22

Example:2
//Write a java program to illustrate readPassword method from console class?
import [Link];
class ReadPasswordTest
{
public static void main(String args[]){
Console c=[Link]();
[Link]("Enter password: ");
char[] ch=[Link]();
String pass=[Link](ch);//converting char array into string
[Link]("Password is: "+pass);
}
}
Output:
Enter password:

Password is: welcome777


Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 37

You might also like