Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Java 1,2,3

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java 1,2,3

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Sir C R Reddy College, Eluru.

P.PAVANI
III B.Sc. III-Semester
Subject: Computer Science
Paper: Object Oriented Programming Using Java (Paper-III)

1
III Semester Syllabus

OBJECT ORIENTED PROGRAMMING USING JAVA

UNIT-I

FUNDAMENTALS OF OBJECT – ORIENTED PROGRAMMING: Introduction, Object


Oriented paradigm, Basic Concepts of OOP, Benefits of OOP, Application’s of OOP.

OVERVIEW OF JAVA LANGUAGE: Introduction, java features Simple Java program


structure, difference between C, C++ and java, java and internet, Java tokens, Java Statements,
Implementing a Java Program, Java Virtual Machine, Command line arguments.

CONSTANTS, VARIABLES & DATA TYPES: Introduction, Constants, Variables, Data


Types, Declaration of Variables, Giving Value to Variables, Scope of variables, Symbolic
Constants, Type casting, Getting Value of Variables, Standard Default values;

UNIT-II

OPERATORS AND EXPRESSIONS : Arithmetic operators Relational operators, logical


operators, Assignment operators, Increment and decrement operators, Conditional operators,
Bitwise operators, Special operators, Arithmetic operators, Precedence of Arithmetic operators.

DECISION MAKING & BRANCHING: Introduction, Decision making with if statement,


Simple if statement, if Else statement, Nesting of if else statements, the else if ladder, the switch
statement, the conditional operator.

DECISION MAKING & LOOPING: Introduction, The While statement, the do-while
statement, the for statement, Jumps in loops.

CLASSES, OBJECTS & METHODS: Introduction, Defining a class, Adding variables, Adding
methods, Creating objects, Accessing class members, Constructors, Method overloading, Static
members, Nesting of methods, visibility controls.

UNIT-III

INHERITANCE: inheritance and types of inheritances, Extending a class, Overloading


methods, Final variables and methods, Final classes, Abstract methods and classes.

ARRAYS, STRINGS AND VECTORS: Arrays, One-dimensional arrays, Creating an array,


Two – dimensional arrays, Strings, Vectors, Wrapper classes.
INTERFACES: MULTIPLE INHERITANCE: Introduction, Defining interfaces, Extending
interfaces, Implementing interfaces, Assessing interface variables

2
UNIT-IV

MULTITHREADED PROGRAMMING: Introduction, Creating Threads, Extending the


Threads, Stopping and Blocking a Thread, Lifecycle of a Thread, Using Thread Methods, Thread
Exceptions, Thread Priority, Synchronization, Implementing the ‘Runnable’ Interface.

MANAGING ERRORS AND EXCEPTIONS: Types of errors: Compile-time errors, Run-time


errors, Exceptions, Exception handling, Multiple Catch Statements, Using finally statement.

UNIT-V

APPLET PROGRAMMING: local and remote applets, difference between Applets and
Applications, Building Applet code, Applet Life cycle: Initialization state, Running state, Idle or
stopped state, Dead state, Display state Designing web page, adding applet to HTML file,
Running the Applet.

PACKAGES: Introduction, Java API Packages, Using System Packages, Naming conventions,
Creating Packages, Accessing a Package, using a Package, Adding class to a package, Hiding
classes, static Import.

Prescribed Book:

1. E .Balaguru swamy, Programming with JAVA, A primer, 3e, TATA McGraw-Hill Company.

3
UNIT-I

JAVA PROGRAM STRUCTURE

A Java program may contain many classes of which only one class defines a main
method. Classes contain data members and methods that operate on the data members of the
class. Method may contain data type declarations and executable statements.

Documentation Section (Suggested)


Package Statement (Optional)
Import Statements (Optional)
Interface Statements (Optional)
Class Definition (Optional)
Main Method Class (Essential)
{
Main Method Definition
}

Documentation Section:
The documentation section comprises a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to refer to at a later
stage. Java uses a third style of comment /**……..*/ known as documentation comment.

Package Statement:
The first statement allowed in a Java file is a package statement. This statement
declares a package name and informs the compiler that the classes defined here belong to this
package.
Import Statement:
The next thing after a package statement may be a number of import statements. This
is similar to the #include statement in C.

Example: import java.util.Scanner;

Interface Statements:

4
An interface is like a class but include a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance feature
in the program.

Class Definition:
A java program may contain multiple class definitions. Classes are the primary and
essential elements of a java program. These classes are used to map the objects of real-world
problems. The number of classes used depends on the complexity of the problem.

Main Method Class:


Since every java stand-alone program requires a main method as its starting point, this
class is the essential part of a java program.

HOW JAVA DIFFERS FROM C AND C++

Although Java was modeled after C and C++ languages, it differs from C and C++ in
many ways. Java does not incorporate a number of features available in C and C++. For the
benefit of C and C++ programmers.

JAVA AND C:

 Java does not include the C unique statement keywords goto, sizeof, and typedef.
 Java does not contain the data types struct, union and enum.
 Java does not support an explicit pointer type.
 Java does not have a preprocessors #define, #include and #ifdef statements.
 Java adds new operators such as instanceof and >>>.
 java adds many features required for object-oriented programming.

JAVA AND C++:

 Java does not support operator overloading.


 Java does not have template classes as in C++.
 Java does not support multiple inheritance of classes. This is accomplished using a
new feature called “interface”.
 Java does not support global variables. Every variable and method is declared within a
class and forms part of that class.
 Java does not use pointers.
 There are no header files in Java.

JAVA TOKENS
5
A Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Most statements
contain expressions, which describe the actions carried out on data. Smallest individual units
in a program are known as tokens.

Java language includes five types of tokens. They are:

 Reserved Keywords
 Identifiers
 Literals
 Operators
 Separators

Java Character Set:

The smallest units of java language are the characters used to write java tokens. These
characters are defined by the Unicode character set. Java language currently supports more
than 34,000 defined character derived from 24 languages.

Reserved Keywords:

Keywords are an essential part of a language definition. They implement specific


features of the language. Java language has reserved 60 words as keywords. Since keywords
have specific meaning in java, we cannot use them as names for variables, classes, methods
and so on. All keywords are to be written in lower-case letters.
Example: int, float, if, for, while………

Identifiers:

Identifiers are programmer-designed tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program. Java identifiers
follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
Kool
Literals:

Literals in java are a sequence of characters that represent constant values to be stored
in variables. Java language specifies five major types of literals.
They are:

6
1. Integer literals
2. Floating-point literals
3. Character literals
4. String literals
5. Boolean literals

Operators:

An operator is a symbol that takes one or more arguments and operates on them to
produce a result.

Example: Arithmetic operators


Relational operators………

Separators:

Separators are symbols used to indicate where groups of code are divided and
arranged. They basically define the shape and function of our code.
Example: parentheses()
Braces{}……..

JAVA VIRTUAL MACHINE (JVM)

All language compilers translate source code into machine code for a specific
computer. Java compiler also does the same thing. Java compiler produces an intermedia
code known as bytecode for a machine that does not exist. This machine is called the java
virtual machine and it exists only inside the computer memory.

Process of compilation
Java Program Java Compiler Virtual Machine
Ja
Source Code Bytecode

The virtual machine code is not machine specific. The machine specific code is
generated by the java interpreter by acting as an intermediary between the virtual machine
and the real machine. Remember that the interpreter is different for different machines.
Process of converting bytecode into machine code
Bytecode Machine Code
Java Interpreter
Ja
Virtual machine Real Machine

COMMAND LINE ARGUMENTS

7
There may be occasions when we may like our program to act in a particular way
depending on the input provided at the time of execution. This is achieved in java programs
by using what are known as command line arguments. These are parameters that are supplied
to the application program at the time of invoking it for execution.

We can write java programs that can received and use the arguments provided in the
command line. The signature of the main method is public static void main(String args[]).
Here args[] is declared as an array of strings any argument provided in the command line are
passed to the array args[] as its emements.

Example: class Sample


{
public static void main(String args[])
{
int i=0;
System.out.println(“Command line arguments”);
for(i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}

Compile and run the program with the command line as follows:

java Sample C CPP Java

The output of the program would be as follow:

Command line arguments

C
CPP
Java

VARIABLES

A variable is an identifier that denotes a storage location used to store a data value. A
variable may take different values at different times during the execution of the program.
A variable name can be chosen by the programmer in a meaningful way so as to
reflect what it represents in the program.

8
Example:

average
height
total_height

A variable name may consist of alphabets, digits, the underscore(_) and dollar
character, subject to the following conditions:

 They must not begin with a digit.


 Uppercase and Lowercase are distinct.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.

Declaration of Variables:

In Java, variables are the names of storage locations. After designing suitable variable
names, we must declare them to the compiler. Declaration does three things:

 It tells the compiler what the variable name is.


 It specifies what type of data the variable will hold.
 The place of declaration decides the scope of the variable.

Variables are separated by commas. A declaration statement end with a semicolon.

Example:

int count,x,y;

Giving Values to Variables:

A variable must be given a value after it has been declared but before it is used in an
expression. This can be achieved in two ways:

1. By using an assignment statement


2. By using a read statement

Assignment statement:

A simple method of giving value to a variable is through the assignment statement as


follows:
variableName = value;

9
Example:
count=100;
x=200;

Read statement:

We may also give values to variables interactively through the keyboard using the
Scanner class methods.

Example:

import java.util.Scanner;
class Values
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int x;
System.out.println(“Enter x value”);
x=in.nextInt();
System.out.println(“X Values is “ +x);
}
}

Scope of Variables:

Java variables are actually classified into three kinds:

1. instance variables
2. class variables
3. local variables
Instance and class variables are declared inside a class. Instance variables are created
when the objects are instantiated and therefore they are associated with the objects. Class
variables are global to a class and belong to the entire set of objects that class creates.

Variables declared and used inside methods are called local variables. They are called
so because they are not available for use outside the method definition. Local variables can
also be declared inside program blocks that are defined between an opening brace

Example:
10
class Variable
{
public static void main(String args[])
{
int x=100; \\class variable
void getData()
{
int y=200; \ \local variable
}
}
}
DATA TYPES
Every variable in java has a data type. Data types specify the size and type of values
that can be stored. Java language is rich in its data types. The variety of data types available
allows the programmer to select the type appropriate to the needs of the application.

DATA TYPES IN JAVA

Primitive Non-Primitive
(Intrinsic) (Derived)

Numeric Non-Numeric Classes Arrays

Interfaces
Integer Floating Character Boolean

Integer Types:

Integer types can hold whole numbers such as 123, -96, and 5639. The size of the value that
can be stored depends on the integer data type we choose. Java supports four types of integer.

Data Type Size Minimum value Maximum value

11
byte 1 byte -128 127

short 2 bytes -32,768 32,767

int 4 bytes -2,147,483,648 2,147,483,647

long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating Point Types:

Integer types can hold only whole numbers and therefore we use another type known
as floating point type to hold numbers containing fractional parts such as 27.59 and -1.375.
There are two kinds of floating point storage in java.
Type Size Minimum value Maximum value

float 4 bytes 2.4e-038 3.4e+038

double 8 bytes 1.7e-308 1.7+308

Floating point numbers are treated as double-precision quantities. To force them to be


in single-precision mode, we must append f or F to the numbers.
Example:
1.23f
7.56923F

Character Type:

In order to store character constants in memory, Java provides a character data type
called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single
character.

Boolean Type:

Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two values that a Boolean type can take: true or false. Boolean
type is denoted by the keyword Boolean and uses only one bit of storage.

TYPE CASTING

12
There is a need to store a value of one type into a variable of another type. In such
situations, we must cast the value to be stored by preceding it with the name in parentheses.

Syntax: type variable1=(type) varaible2;

Example: int m=50;


byte n=(byte) m;
long count=(long) m;

Four integer types can be cast to any other type except Boolean. Casting into a smaller
type may result in a loss of data. Similarly, the float and double can be cast to any type except
Boolean.

Automatic Conversion: For some types, it is possible to assign a value of one type to a
variable of a different type without a cast. Java does the conversion of the assigned value
automatically. This is known as automatic type conversion.

Example: byte b=75;


int a=b;

Imp Questions:
13
10 Marks important questions

1. Explain Basic Concepts of OOPs.


2. Write about Java Features.
3. Explain Data Types available in java.
4. Explain different types of operators.

5 Marks important questions

1. Benefits of OOP.
2. Write the applications of OOP.
3. Java program structure.
4. Explain JVM.
5. Explain command line arguments.

UNIT-II
14
OPERATORS

Java supports a rich set of operators. An operator is a symbol that tells the computer
to perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They usually form a part of mathematical or logical
expressions.
Java operators can be classified into a number of related categories as below:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic Operators:

Java provides all the basic arithmetic operators. The operators +, -, *, /, and % all
work the same way as they do in other languages. These can operate on any built-in numeric
data type of Java. We cannot use these operators on Boolean type.
Operator Meaning

+ Addition of unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division

Arithmetic operators are used as shown below:


a-b a+b
a*b a/b
a%b

Relational Operators:

We often compare two quantities, and depending on their relation, take certain
decisions. For example, we may compare the age of two persons, or the price of two items,
and so on. These comparisons can be done with the help of relational operators.

15
Java supports six relational operators in all. These operators and their meanings are
shown in below:
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

A simple relational expression contains only one relational operator and is of the
following form:

ae-1 relational operator ae-2


ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them.

Logical Operators:
Java has three logical operators, which are given below:
Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

The logical operators && and || are used when we want to form compound conditions
by combining two or more relations.
Example
a>b && b<c
Truth Table
op-1 op-2 op-1 && op-2 op-1 || op-2
true True true true
true False false true
false True false true
false False false true
Note:
 op-1 && op-2 is true if both op-1 and op-2 are true and false otherwise.
 op-1 || op-2 is false if both op-1 and op-2 are false and true otherwise.

16
Assignment Operators:

Assignment operators are use to assign the value of an expression to a variable. The
usual assignment operator ‘=’. In addition, Java has a set of shorthand assignment operator
which are used in the form:
v op=exp;
Where v is a variable, exp is an expression and op is a java binary operator. The
operator op= is known as the shorthand assignment operator.
Example
x + = y+1; This is same as the statement x = x+(y+1);
Shorthand Assignment Operators
Statement with simple assignment Statement with shorthand operator
operator
a = a+1 a += 1
a = a-1 a -= 1
a = a*(n+1) a *= n+1
a = a/(n+1) a /= n+1
a = a%b a %= b

Increment and Decrement Operators:

Java has two very useful operators not generally found in many other languages.
These are the increment and decrement operators:
++ and --
The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators
and are used in the following form:
++m; or m++
--m; or m—
++m; is equivalent to m = m + 1; (or m += 1)
--m; is equivalent to m = m – 1; (or m -= 1)

Conditional Operator:

The character pari ?: is a ternary operator available in java. This operator is used to
construct conditional expressions of the form
exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions.
The operator ?: works as follows: exp1 is evaluated first. If it is nonzero (true), then
the expression exp2 is evaluated and becomes the value of the conditional expression. If exp1
is false, exp3 is evaluated and its value becomes the value of the conditional expression.

17
Example:

x = ( a > b ) ? a : b;

Bitwise Operators:

Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or double.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Left shift
>> Right shift
>>> Right shift with zero fill

Dot Operator:

The dot operator(.) is used to access the instance variables and methods of class
objects.
Example
person1.age /Reference to the variable age
person1.salary /Reference to the method salary()
It is also used to access classes and sub-packages from a package.
DECISION MAKING & BRANCHING STATEMENTS

When a program breaks the sequential flow and jumps to another part of the code, it is
called branching. When the branching is based on a particular condition, it is known as
conditional branching. If branching takes place without any decision, it is known as
unconditional branching.
Java language possesses such decision making capabilities and supports the following
statements known as control or decision making statements.
1. if statement
2. switch statement
3. conditional operator statement

DECISION MAKING WITH IF STATEMENT

18
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression.
Syntax:
if( test expression)
It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression is true or false, it transfers the control to a particular statement.

Entry

test False
expressio
n

True

The if statement may be implemented in different forms depending on the complexity


of conditions to be tested.
1. Simple if statement
2. if..else statement
3. Nested if..else statement
4. else if ladder

Simple if statement:

The general form of a simple if statement is


if(test expression)
{
statement-block;
}
statement x;

The statement block may be a single statement or a group of statements. If the test
expression is true, the statement-block will be executed; otherwise the statement-block will
be skipped and the execution will jump to the statement x.

The if…else statement:

The if…else statement is an extension of the simple if statement. The general form is

19
if(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement x

If the test expression is true, then the true-block statement(s) immediately following
the if statement, are executed; otherwise, the false-block statement(s) are executed. In either
case, either true-block or false-block will be executed, not both. In both the cases, the control
is transferred subsequently to the statement x.

Nesting of if…else statement:

When a series of decisions are involved, we may have to use more than one if…else
statement in nested form as follows:

if(test condition1)
{
if(test condition2)
{
Statement-1;
}
else
{
Statement-2;
}

}
else
{
Statement-3;
}
Statement-x;

The logic of execution is if the condition-1 is false, the statement-3 will be executed;
otherwise it continues to perform the second test. If the condition-2 is true, the statement-1
will be evaluated; otherwise the statement-2 will be evaluated and then the control is
transferred to the statement-x.

20
The else if ladder:

There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of ifs in which the statement associated with each else is an if. It
takes the following general form:

if(condition-1)
{
Statement-1;
}
else
{
if(condition-2)
{
Statement-2;
}
else
{
if(condition-3)
{
Statemet-3;
}
else
{
if(condition n)
{
Statement-n;
}
else
{
Default-statement;
}
}
}
}
Statement-x;

This construct is known as the else if ladder. The conditions are evaluated from the
top (of the ladder), downwards. As soon as the true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x. When all the n
conditions become false, then the final else containing the default-statement will be execute.

DECISION MAKING WITH SWITCH STATEMENT

21
Switch statement:

Java has a built-in multi-way decision statement known as a switch. The switch
statement is found, a block of statements associated with that case is executed. The general
form of the switch statement is as shown below:

switch ( expression )
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…………….
…………….
default:
default-block
break;
}
statement-x;

Here the expression is an integer expression or character. Value-1, value-2… were


constants or constant expressions and are known as case labels. Each of these values should
be unique within a switch statement. Block-1, block-2…..are statement lists and may contain
zero or more statements. There is no need to put braces around these blocks but it is
important to note that case labels end with a colon ( : ).
When the switch is executed, the value of the expression is successively compared
against the values value-1, value-2,…. If a case is found whose value matches with the value
of the expression, then the block of a statement that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement, transferring the control to the statement-x following
the switch.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes place
when all matches fail and the control goes to the statement-x.
The Conditional Statement (?:):

The Java language has an unusual operator, useful for making two-way decisions.
This operator is a conditional of ? and :, and takes three operands. This operator is popularly
known as the conditional operator. The general form of use of the conditional operator is as
follows:

22
Conditional expression ? expression-1 : expression-2
The conditional expression is evaluated first, if the result is true, expression-1 is
evaluated and returned as the value of the conditional expression. Otherwise, expression-2 is
evaluated and its value is returned.
Example:
if ( x > 0 )
flag=0;
else
flag=1;
can be written as
flag = ( x > 0 ) ? 0 : 1;

CONSTRUCTORS:

Java supports a special type of method, called a constructor that enables an object to initialize
itself when it is created. Constructors have the same name as the class itself. Secondly, they do not
specify a return type, not even void. This is because they return the instance of the class itself.

Ex:

class Constructor
{
int a,b;
Constructor(int x,int y)
{
a=x;
b=y;
System.out.println(+(a+b));
}
}
class Constructor1
{
public static void main(String args[])
{
Constructor c=new Constructor(100,100);
}
}

METHODS OVERLOADING:
In java , it is possible to create methods that have the same name, but different parameter lists
and different definitions. This is called method overloading. Method overloading is used when objects
are required to perform similar tasks but using different input parameters. When we call a method in
an object, java matches up the method name first and then the number and type of parameters to
decide which one of the definitions to execute. This process is known as polymorphism.

23
To create an overloaded method, all we have to do is to provide several different method
definitions in the class, all with the same name, but with different parameter lists. The difference may
either be in the number or type of arguments.

Ex:

class MethodOver
{
int a,b;
MethodOver(int x) //constructor
{
a=x;
System.out.println(+a);
}
MethodOver(int x,int y) //constructor and overloaded method
{
a=x;
b=y;
System.out.println(+(a+b));
}
}
class Over
{
public static void main(String args[])
{
MethodOver m=new MethodOver(100);
MethodOver m1=new MethodOver(100,200);
}
}

STATIC MEMBERS:

A class basically contains two sections. One declares variables and the other declares
methods. These variables and methods are called instance variables and instance methods. Because
every time the class is instantiated, a new copy of each of them is created. They are accessed using the
objects(with dot operator).

static int count;

static void max(int x, int y);

Them members that are declared static as shown above are called static members. Since these
members are associated with the class itself rather than individual objects, the static variables and
static methods are often referred to as class variables and class methods in order to distinguish them
from their counterparts, instance variables and instance methods.

Static variables are used when we want to have a variable common to all instance of a
class. Static variables, static methods can be called without using the objects.

24
Ex:

class Static
{
int a=100,b=200;
void add()
{
System.out.println(+(a+b));
}
void sub()
{
System.out.println(+(a-b));
}
}
class StaticTest
{
public static void main(String args[])
{
Static.add();
Static.sub();
}
}

Imp Questions:

10 Marks important questions

1. Explain different forms of if statement.


2. Explain looping statements in java.

5 Marks important questions

1. Explain switch statement.


2. Explain conditional operators.
3. Explain constructors.
4. Explain method overloading.
5. Write about static methods and classes.

UNIT – III

INHERIRANCE:
Reusability is yet another aspect of OOP paradigm. Java classes can be reused in
several ways. This is basically done by creating new classes, reusing the properties of
existing ones.

25
The mechanism of deriving a new class from an old one is called inheritance. The
old class is known as the base class or super class or parent class and the new one is called
the sub class or derived class or child class.

Defining a Subclass:
A subclass is defined as follows:
class subclassname extends superclassname
{
variables declaration;
methods declaration;
}

Types (OR) Various Forms of Inheritances:


The inheritance allows subclasses to inherit all the variables and methods of their
parent classes. Inheritance may take different forms:

1. Single inheritance (only one super class)


2. Multilevel inheritance (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multiple inheritance (derived from a derived class)

Then keyword extends signifies that the properties of the superclassname are extended to
the subclassname. The subclass will now contain its own variables and methods as well those
of the super class.

Single Inheritance:

A Super class

B
Sub class

class A
{
int a=100;b=200;
}
class B extends A
{
public void add()
{
System.out.println(“Addition is “+(a+b));
}
}
class C
{

26
public static void main(String args[])
{
B b1=new B();
b1.add();
}
}

OUTPUT:
Addition is 300

Multilevel Inheritance: A common requirement in object-oriented programming is the use


of a derived class as a super class.
A

The class A serves as a base class for the derived class B which in turn serves as a base class
for the derived class C. The chain ABC is known as inheritance path.
A derived class with multilevel base classes is declared as follows.
class A
{
………….
………….
}
class B extends A //First level
{
………….
………….
}
class C extends B //Second level
{
………….
………….
}
This process may be extended to any number of levels. The class C can inherit the members
of both A and B.

Hierarchical Inheritance: Derivation of several classes from a single base class that is the
trails of one class may be inherited by more than one class is called hierarchical inheritance.

A
27
Multiple Inheritance: Derivation of a class from several base classes is called multiple
inheritance.

A B

OVERRIDING METHODS:
we should override the method defined in the superclass. This is possible by defining
a method in the subclass that has the same name, same arguments and same return type as a
method in the superclass. Then, when that method is called, the method defined in the
subclass in invoked and executed instead of the one in the superclass. This is known as
overriding.

Example:
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
System.out.println(“Super x=”+x);
}
}
class Sub extends Super
{
int y;

28
Sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println(“Super x=”+x);
System.out.println(“Sub y=”+y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();
}
}

FINAL VARIABLES AND METHODS:


The value of a finalized variable cannot be changed.When final is applied to a variable, it
means that the variable is constant.
Methods that cannot be overridden are known as finalized methods. we can declare them as
final using the keyword final as a modifier.
Ex:
final int SIZE = 100;
final void show()
{
}
Making a method final ensures that the functionally defined in this method will never be
altered in any way. Similarly, the value of a final variable can never be changed.

FINAL CLASSES: A class that connot be inherited is called a final class. This is achieved in
java using the keyword final.
Ex:
final class Aclass
{
}
Any attempt to inherit these classes will cause an error and the compiler will not allow it.

ABSTRACT METHODS AND CLASSES: final method is not redefined in a subclass.


That is, the method can never be subclassed. Java allows us to do something that is exactly
opposite to this. That is, we can indicate that a method must always be redefined in a
subclass, thus making overriding compulsory. This is done using the modifier keyword
abstract in the method definition.
Ex:
abstract class Shape
{
…………

29
…………
…………
abstract void draw()
…………
}
While using abstract classes, we must satisfy the following conditions.
 We cannot use abstract classes to instantiate objects directly.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.

VISIBILITY CONTROL OR VISIBILITY MODIFIERS:


Java provides three types of visibility modifiers:
 public
 protected
 private

Public access: Any variable or method is visible to the entire class in which it is defined. We
make them visible to all the classes outside this class by declaring them as public.
Ex:
public int a;
public void display();
A variable or method declared as public has the widest possible visibility and accessible
everywhere.

Protected access: The visibility level of a protected field lies in between the public access
and friendly access. That is, the protected modifier makes the fields visible not only to all
classes and subclasses in the same package but also to subclasses in other packages, but non-
private method in a subclass and then make it private.

Private access: private fields enjoy the highest degree of protection. They are accessible only
with their own class. They cannot be inherited by subclasses. A method declared as private
behaves like a method declared as final.

ARRAYS, STRINGS AND VECTORS

ARRAY: An array is a group of contiguous or related data items that share a common name.
CREATIN AN ARRAY: Array must be declared and created in the computer memory
before they are used. Creation of an array involves three steps.
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.

Declaration of Arrays: Array in java may be declared in two forms.


Form1: type arrayname[];
Form2: type[] arrayname[];
Examples:
int number[];
float average[];

30
Creation of Arrays: After declaring an array, we need to create it in the memory. Java
allows us to create arrays using new operator only.
arrayname = new type[size];
Examples:
number =new int[5];
average =new float[10];

Put values into the memory locations: The final step is to put values into the array created.
This process is known as initialization. This is done using the array subscript.
arrayname[subscript]=value;
Example:
number[0]=35;
number[1]=40;
number[2]=50;
number[3]=55;
number[4]=60;
int number[]={35,40,50,55,60};

TYPES OF ARRAYS:

ONE-DIMENSIONAL ARRAYS: A list of items can be given one variable name using
only one subscript and such a variable is called a single-subscripted variable or a one-
dimensional array.

The subscript can began with number 0.


Example:
int number[]=new int[5];
and the computer reserves five storage locations as shown below:
number[0]

number[1]

number[2]

number[3]

number[4]

The values to the array elements can be assigned as follows:


int number[]={35,40,20,57,19};

number[0]=35
number[1]=40
number[2]=20
number[3]=57
number[4]=19

Example program:
class NumberSorting

31
{
public static void main(String args[])
{
int number[]={55,40,80,65,71};
int n=numer.length;
System.out.println(“Given list:”);
for(int i=0;i<n;i++)
{
System.out.println(“”+number[i]);
}
System.out.println(“\n”);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]>number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
System.out.println(“Sorted list”);
for(int i=0;i<n;i++)
{
System.out.println(“”+number[i]);
}
}
}
TWO-DIMENSIONAL ARRAYS: For creating two-dimensional arrays, we must
follow the same steps as that of single arrays. We may create a two-dimensional array like
this:
int myArray[][];
myArray = new int[3][4];

(or)
int myArray[][] = new int[3][4];

This creates a table that can store 12 integer values, four across and three down.

Example program:
class MulTable
{
int rows=20;
int columns=20;
public static void main(String args[])
{
int product[][]=new int[rows][columns];
System.out.println(“Multiplication Table”);

32
int i,j;
for(i=10;i<rows;i++)
{
for(j=10;j<columns;j++)
{
product[i][j]=i*j;
System.out.print(“ ”+product[i][j]);
}
System.out.println(“ ”);
}
}
}

STRINGS
String manipulation is the most common part of many java Programs. Strings
represent a sequence of characters. The easiest way to represent a sequence of characters in
java is by using a character array.
Example: char charArray[]=new char[4];
charArray[0]=’j’;
charArray[1]=’a’;
charArray[2]=’v’;
charArray[3]=’a’;

In java, Strings are class objects and implemented using two classes, namely, String
and StringBuffer. A java string is and instantiated object of the String class.
Syntax: String stringName;
StringName=new String(“string”);
Example: String firstName;
firstName=new String(“anil”);

String class methods


Method name Task performed
s2=s1.toLewerCase; Converts the string s1 to all lowercases
s2=s1.toUpperCase; Converts the string s1 to all Uppercase
s2=s1.replace(‘x’,’y’); Replace all appearances of x with y
s2=s1.trim(); Remove white spaces at the beginning and end
of the string s1
s1.equals(s2) Returns ‘true’ if s1 is equal to s2
s1.length() Gives the length of s1
s1.concat(s2) Concatenates s1 and s2

StringBuffer Class: StringBuffer is a peer class of String. While String


createsstrings of fixed_length, StringBuffer creates strings of flexible length that can be
modified in terms of both length and content. We can insert characters and substrings in the
middle of a string, or append another string to the end.

Method Task performed

33
s1.setChartAt(n, ‘x’) Modifies the nth character to x
s1.append(s2) Append the string s2 to s1 at the end
s1.insert(n,s2) inserts the string s2 at the position n of the string
s1
s1.setLength(n) Sets the length of the string s1 to n.
Example program:
class StringTest
{
void display()
{
String s=new String(“String Test”);
String s1=new String(“Example”);
StringBuffer s2=new StringBuffer(“String Buffer”);
StringBuffer s3=new StringBuffer(“Example”);
System.out.println(s.toUpperCase());
System.out.println(s1.toLowerCase());
System.out.println(s1.replace(‘E’,’e’));
System.out.println(s.trim());
System.out.println(s.equals(s1));
System.out.println(s.length());
System.out.println(s1.length());
System.out.println(s3.setChartAt(1,’e’));
System.out.println(s2.append(s3));
}
}
class StringTest1
{
public static void main(String args[])
{
StringTest st=new StringTest();
s1.display();
}
}

INTERFACES (MULTIPLE INHERITANCE):


Java does not support multiple inheritance. That is, classes in java cannot have more
than one superclass. Java provides an alternate approach known as interface to support the
concept of multiple inheritance. Although a java class cannot be a subclass of more than one
superclass, it can implement more than one interface, thereby enabling us to create classes
that build upon other classes without the problems created by multiple inheritance.

DEFINING INTERFACES:
An interface is basically a kind of class. Like classes, interface contain methods and
variables but with a major difference. The differences are that interfaces define only abstract
methods and final fields. This means that interfaces do not specify any code to implement
these methods and data fields contain only constants.
The syntax for defining an interface is very similar to that for defining a class. The
form of an interface definition is:
Syntax:
interface interfacename

34
{
variable declaration;
methods declaration;
}
Example:
interface Area
{
final static float pi=3.14F;
float compute(float x, float y);
void show();
}

EXTENDING INTERFACES:
Like classes, interfaces can also be extended. That is, an interface can be
subinterfaced from other interfaces. The new subinterface will inherit all the members of the
superinterface in the manner similar to subclasses.
Syntax: interface name2 extends name1
{
body of name2
}

Example: interface ItemConstants


{
int code=1001;
}
interface Item extends ItemConstants
{
void display();
}

IMPLEMENTING INTERFACES:
Interfaces are used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
Syntax: class classaname implements interfacename
{
body of classname
}

VARIOUS FORMS OF INTERFACE IMPLEMENTATION:


A Interface A Class D Interface

Implements Extends Extends

35
B B Implements E
Class Class Interface

Extends Extends

C Interface C Class

(a) (b)

A
Interface

Implements

B C
Class Class

(c)

A Interface B Interface

Extends

c
Interface

Implements

D
Class
(d)
Example program:
class Student
{
int rollNumber;
void getNumber(int n)
{

36
rollNumber=n;
}
int putNumber()
{
return(rollNumber);
}

}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putMarks()
{
System.out.println("Marks obtained ");
System.out.println("part1="+part1);
System.out.println("part2="+part2);
}
}
interface Sports
{
float sportWt=6.0F;
void putWt();
}
class Results extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println("Sports Wt="+sportWt);
}
void display()
{
total=part1+part2+sportWt;
System.out.println("Roll no"+putNumber());
putMarks();
putWt();
System.out.println("Total score="+total);
}
}
class Hybrid
{
public static void main(String args[])
{
Results student1=new Results();
student1.getNumber(1234);

37
student1.getMarks(27.5F,33.0F);
student1.display();
}
}

Imp questions:
1. What is an inheritance? Explain types of inheritances.
2. Explain method overriding.
3. Explain abstract classes and methods.
4. What is an array? Explain types of arrays.
5. What is string? Explain any five String and StringBuffer class methods.
6. What is an interface? Explain various forms of interface implementation.
7. What is an interface? How to extend and implementing interfaces in java.

38

You might also like