Java Notes (II - Unit) Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Chaitanya Degree College B.Sc.

III Year V Sem (Java Notes)


Unit II
Operators: An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. These are used in the programs to manipulate data and variables. In Java the
operators are classified as below.
1. Arithmetic Operators: these are used to construct mathematical expressions as in algebra.
The Arithmetic Operators are + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulo
division/Remainder).
When both the operands in a single arithmetic expression are integers then the result is an
integer value, such operation is called integer arithmetic operation.
Ex: if a=10, b=3 then a/b=3.
When both the operands in a single arithmetic expression are real then the result is a real value, such
operation is called Real arithmetic operation.
Ex: if a=55.55, b=1.1f then a/b=50.5
When one of the operands is real and other is integer the expression is called a mixed-mode
arithmetic operation. Then the result will be a real.
Ex: 26/4.0 gives 6.5 and 26/4 gives 6.
2. Relational Operators: Relational Operators are used to compare two quantities. The value of
relational expression is either true or false. Java supports six relational operators.
1. < less than 2. <= less than or equal to
3. > greater than 4. >= greater tan or equal to
5. == equal to 6. != not equal to
3. Logical Operators: Java has three logical operators. These are used when we want to perform
compound conditions by combining two or more relations. Such expressions are called logical
expressions. The output of such expression is either true or false.
1. && logical AND 2. || logical OR 3. ! logical NOT
4. Assignment Operators: Assignment Operators are used to assign the value of an expression to
a variable. Java has a set of shorthand assignment operators. Some examples are:
1. a = a+1 ➔ a + =1 2. a = a-1 ➔ a -= 1
5. Increment and Decrement operators: Java has two useful operators ++ and --. These are
called Increment and Decrement operators, used mainly in for and while loops.
Ex: m++ is equal to m=m+1 or m +=1. m-- is equal to m=m-1 or m-=1.
6. Conditional Operator: The character pair ? : is called Conditional Operator in Java.
Syntax: exp1 ? exp2 : exp3
in the above syntax exp1 is used as condition when it is true exp2 is evaluated, when it is false exp3
is evaluated. This is substitute for if…else statement.
7. Bitwise Operators: Java supports special operators called bitwise operators for manipulation of
data at bit level. These operators are not applied to float and double. They are

Operator Use class bitwise


& Bitwise AND { Output:
! Bitwise OR public static void main(String args[ ]) a =11
^ Bitwise { b =19
Exclusive OR int a=11, b=19; a & b =3
~ One’s System.out.println("a ="+a+"\nb ="+b); a | b =27
Complement System.out.println("a & b ="+(a&b)); a ^ b =24
<< Shift left
System.out.println("a | b ="+(a|b)); a >>2 =2
>> Shift right a <<3 =88
System.out.println("a ^ b ="+(a^b));
>>> Shift right with System.out.println("a >>2 ="+(a>>2)); a >>>2 =4
zero fill ~a =-12
System.out.println("a <<3 ="+(a<<3));
Program to demonstrate
System.out.println("a >>>2 ="+(b>>>2));
Bitwise Operators System.out.println("~a ="+(~a));
}
}
Unit II 1
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
8. Special Operators: Java supports some special operators like instanceof operator and member
selection operator dot(.).
The instanceof is an object reference operator and returns true if the object on the left hand
side is and instance of the class given on the right hand side. It is used to determine whether the
object belongs to a particular class or not.
Ex: parrot instanceof bird (it is true if the object parrot belongs to class bird,
other wise it is false)
The dot operator is used to access the instance variables and methods of class objects.
Ex: person.age (Reference to variable age)
Type Conversion in Expressions: An expression may have at least one operator and two
operands, these operands may be different data types, the lower type is automatically converted to
the higher type before the operation proceeds. The result is always higher type.
If byte, short and int variables are used in any expression, the result is always int. if long is
used in expression the result is promoted to long. All integers are considered as int unless they have
the l or L appended to them. If an expression consists a float or double, the result is promoted to float
and double respectively. Java automatically converts the results to higher data type this is called
automatic type conversion.
Casting a Value: Java performs type conversion automatically. If we want to convert a variable or
value to another data type we have to type the type name in the parentheses before that variable or
expression.
Ex: x = (double)sum/n (sum is converted into double and performs floating point
division)
Operator precedence and associatively: Each operator in Java has precedence with it.
Precedence determines the order how the expression is evaluated. The operators of higher level of
precedence (Lower Rank) are evaluated first. The operators of same precedence are evaluated
either from left to right or right to left. This order is called associativity. The precedence of operators
are like below
Operator Name Associativity Rank
. ,( ), [ ] Member selection, function call, Array element reference Left to right 1
-,++,--, Unary minus, Increment, Decrement Right to left 2
!,~,(type) Logical negation, Ones complement, Casting
*, / , % Multiplication, Division, Modulus Left to right 3
+, - Addition, Subtraction Left to right 4
<<, >>, >>> Left shift, Right shift, Right shift with zero fill Left to right 5
<, <=, >, >=, Less than, Less than or equal to, Greater than, Greater Left to right 6
instanceof than or equal to, Type comparison
= =, ! = Equality, Inequality Left to right 7
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Operator Right to left 13
=, op = Assignment operators, Shorthand assignment Right to left 14
Mathematical Functions: java supports mathematical functions through Math class defined in the
java.lang package. The available mathematical functions are:
Function Use Function Use
sin(x) The sine value of x in radians log(x) natural logarithm of x
cos(x) The cosine value of x in radians sqrt(x) Square root of x
tan(x) The tangent value of x in radians ceil(x) Smallest whole no. >= x
asin(x) The angle whose sine is x floor(x) Largest whole no. <=x
acos(x) The angle whose cosine is x rint(x) The truncated value of x
atan(x) The angle whose tangent is x round(x) The integer closed to the argument
atan2(x,y) The angle whose tangent is x/y abs(x) Absolute value of x
pow(x,y) x power of y (xy) max(a, b) The maximum of a and b
exp(x) e raised to x (ex) min(a, b) The minimum of a and b
Unit II 2
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Decision Making and Branching
A program may executed sequentially form top to bottom in normal situations, but in some
situations we may change the order of execution of statements based on certain conditions or repeat
a group of statements until a certain condition is met. It involves decision making. When a program
breaks the sequential flow and jumps to another part of the code, it is called branching. When
branching is based on certain condition it is called conditional branching. Java provides many
statements for decision making they are called control or decision making statements. They are:
1. if statement 2. switch statement 3. conditional operator statement.
Decision making with if statement: if statement is a powerful decision making statement, it has
different forms. They are:
Entry
1. Simple if statement: simple if statement checks
a test expression/condition when that is true it
executes all the statements in if block, otherwise it
skips those statements.
test True
Syntax: expression
If (text expression)
{
Statements – block;
Statements block
}
Ex: If (x>0)
False
{
System.out.print(“ x is positive”);
}
When x>0 it prints “x is positive” otherwise it Exit
Skips the statement. Flowchart
2. The if…else statement: if the test expression is true it executes the true block statements
otherwise it executes false block statements.
Entry
Syntax:
If (text expression)
{
True-block statements;
} False test True
Else expression
{
False-block statements;
} True block statements
False block statements
Ex:
If (x>0)
System.out.print(“ x is positive”);
else
System.out.print(“ x is negative”);
When x>0 they it prints “x is positive” Exit
Otherwise It prints “x is negative.
3. Nesting of if….else statements: When a series of decisions are involved, we
Syntax: if (test condition 1) have to use more than one if…else statements in
{ nested form.
If (test condition 2) When the condition-1 is false Block-3
{ statements will be executed, otherwise it continues to
Block-1 statements; test the condition-2. when the condition-2 is true
} Block-1 statements will be executed other wise Block-
Else 2 statements are executed.
{
Condition-1 Condition-2 Executed block
Block-2 statements:
} True True Block-1 statements
} True False Block-2 statements
else False True Block-3 statements
{ False False Block-3 statements
Block-3 statements;
Unit II 3
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Entry

False test True


Condition-1

False test True


Condition-2

Block-3 statements Block-2 statements Block-1 statements


block

Flowchart of nested if…statement Exit

4. The if…else ladder: It is used perform operations of multiple conditions. When conditions are
more we may use if…else ladder. The conditions are evaluated for the top to bottom. When any
condition is found true the statements associated with it are executed and the control skips the rest of
the conditions, when all the conditions are false it executes the statements under else (default
statements) will be executed.
Syntax: Entry
If (Condition 1)
True
Block -1 statements; Condition 1 Block-1 statements
else if (Condition 2)
Block-2 statements; False

else if (Condition 3)
Condition 2 True Block-2 statements
Block-3 statements;

False
else if (Condition n)
Block-n statements; True
Condition 3 Block-3 statements
else
default-statemensts; False
Ex: If (ave>=70)
Condition n True
Grade=’A’; Block-n statements

else if (ave>=60)
False
Grade = ‘B’;
else if (ave>=50) Default-statements

Grade = ‘C’; Exit


else Flowchart of if….. else ladder
Grade = ‘D’;
The Switch Statement: When we want to select one of many alternative options we have to use
if…else if ladder. But it increases the complexity of the program. Java provides another statement
known as switch. The switch statement tests a value for given variable or expression against a list of
case values and when a match is found, a block of statements associated to that case will be
executed. Every case label must end with a colon(:). The break statement after every case is used
to move the control to out side of the Switch block. The last one default is optional when there is no
match in all the cases it executes the default block statements.
Unit II 4
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Syntax:
switch ( expression) Entry
{
switch
case value-1: expression
block-1 statements;
break;
case value-2: case value 1

block-2 statements; Block-1 statements


break;
Block-2 statements
case value-3: case value 2
block-3 statements;
…………….
break; …………….
:::::::::::::: …………….
::::::::::::::
default: default ( no match)
Default block
default-block;
Exit
break;
}
The Conditional Operator statement: This is the combination of ? and : used to select one option
from two options. We may use this in place of if…. else. This is the simplified form of if… else.
Syntax: conditional expression ? expression1 : expression2
When the conditional expression is true it executed expresion1 otherwise executes expression2.
Decision Making and Looping
Some times we have to perform repetitive operations. The process of repeatedly executing a block of
statements is called looping. The statements in a block may be executed a number of times, if a loop
continues for ever that is called infinite loop. The loop statement consist two sections body of the
loop and control statement. The control statement tests a certain condition and based on the
condition it repeats the execution of the statements in the body of the loop.
Based on the position of the control statement loops are classified into two types:
1. entry-controlled loops: The entry-control loops the conditions are tested before the start
of the loop execution. If the condition is not satisfied the body of the loop will not be executed.
2. exit-controlled loops: The exit-control loops the condition is tested after executing the
statements in the body of the loop. So it is executed for the first time unconditionally.
A loop may contain four items: They are
1. Setting and initialization of counter.
2. Execution statements in the loop (body of the loop).
3. Test for a condition (control statement)
4. Incrementing the counter,
Java provides three types of loops 1. while construct 2. do construct 3. for construct.
1. While loop: The while is an entry-control loop. It checks a condition and as long as the condition
is true it executes the statements of the loop. When the condition is false the control moves to next
line Entry
Syntax: Initialization;
While (test condition) Test True Body of the loop
{ condition (statements)
Body of the loop (statements);
} False
Exit
Unit II 5
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
2. do loop or do statement: The do….While loop is and exit-control loop. It executes the
statements at first after that it checks the condition, when the condition is true then it repeats the
execution of the statements which are written in the body of the loop. It executes the statements for
at least once irrespective of condition.
Syntax: Initialization;
do Body of the loop (statements)
{
Body of the loop (statements);
}
While (test condition); Test True
condition
3. For loop: For loop is an entry control loop. It provides
A more concise loop control structure. It allows using False
Initialization, test condition and increment in a single line. Exit
Syntax:
For (initialization; test condition; increment)
{
Body of the loop;
}
Nesting of for Loops: Nesting is possible through using one for loop within another for loop as
below.
For (initialization; test condition; increment)
{
For (initialization; test condition; increment)
Outer {
loop Inner loop
Body of the loop;
}

}
The enhanced for loop: This is also called “for each loop”. It is used to retrieve the elements form a
collection instead of incrementing a value.
Syntax:
For (Type Identifier: Expression)
{
Body of the loop;
}
Here Type represents the data type or object used. Identifier refers to the name of the variable; the
expression is an instance of the java.
Program to demonstrate enhanced for loop:
class forloop
{
public static void main(String args[])
{
String states[]={"Andhra Pradesh", "Orissa" , "Tamilnadu" , "Karnataka" ,"Kerala",};
for (String i:states)
System.out.println(i);
}
}
Jumps in Loops: Some times we have to jump the control from the loop to required place. For this
purpose java provides some statements like break and continue.
break: it is used to exit from the loop and moves to the next line after the loop, when loops are
nested, the break will exit form the loop containing it.
continue: it is used to terminate the loop and continued from the starting. When it is faced by the
control, the control skips the remaining lines in the loop and control moves to the starting iteration
point (test condition.)

Unit II 6
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
while (test condition) do for (initialization; test condition; increment)
{ { {
:::::::::::::::::: ::::::::::::::::: :::::::::::::::::
If (condition) if (condition) if (condition)
break; break; break;
:::::::::::::::::: :::::::::::::::: :::::::::::::::::
} }while(condition) }

while (test condition) do for (initialization; test condition; increment)


{ { {
:::::::::::::::::: ::::::::::::::::: :::::::::::::::::
If (condition) if (condition) if (condition)
continue; continue; continue;
:::::::::::::::::: :::::::::::::::: :::::::::::::::::
} } while(condition) }
Labelled loops: Java allows the user to give label to a block of statements. A label is a valid Java
variable name. We may add labels to loops also then they are called “labeled loops”. For this we
have to place the label before the loop with a colon (:) at the end.
Ex: cdc: for ( ) wgl: {
{ ::::::::::::::::
:::::::::::::: }
}
Here cdc and wgl are labels and cdc is before so it is labeled loop and wgl is labeled block.
break and continue statements are used to jump outside the nearest loop and restart the
current loop respectively. When we want to jump outside nested loop or to continue with the outer
loop we have to use labeled break and labeled continue statements.
Ex: cdc: for ( ) wgl: for( )
{ {
for ( ) for( )
{ {
continue cdc; / continue; break wgl; / break;
} }
} }

Here continue statement restarts the inner for loop, continue cdc; restarts the outer for loop. The
break statement jumps inner loop, break wgl; statement jumps out for loop.
EX: The below given program has to print 20 stars(“*”) in twenty lines but before the we used break
and continue to break the inner loop and continue cdc to restart labeled loop cdc:
class labelloop
{
public static void main(String args[]) When we delete break and
{ continue statements it will
cdc : for(int i=1;i<=20;i++) display 20 stars for 20 lines
{ Output; like below.
System.out.println(" "); * *******************
if(i>10) break; ** *******************
for(int j=1;j<=20;j++) *** *******************
{ * * * * *******************
System.out.print("* "); * * * * * *******************
if(i==j) * * * * * * *******************
continue cdc; * * * * * * * *******************
} ******** *******************
} ********* *******************
} ********** *******************
} *******************

Unit II 7
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Classes, Objects and methods
Java is a true object-oriented programming language, so anything we wish to represent in a
program must be encapsulated in a class. A class defines the state and behavior of the program
components known as objects. Classes create objects and objects use methods to communicate
between them. Methods are just like functions.
Defining a Class: A class is a user-defined data type serves to define properties. Once a class is
defined we can create variables of that type using declarations. In java these variables are called
“instances of classes”. These are the actual objects. The class is defined as below:
class <class name> extends < super class name>
{
fields declaration;
methods declaration;
}
Here we are defining a class using the keyword “class’”. The keyword extends indicates that the
properties of super class are extended to the defined class, that is an option.
Fields declaration: Data is encapsulated in a class by placing data fields in the class. These
variables are called “instance variables”. These are declared just as local variables;
class triangle The class triangle has two integer type instance variables.
{ We may declare the variables in a single line also.
int length; These variables are also called member variables.
int width;
}
Methods Declaration: A class with only data fields has no life. Such classes cannot respond to any
messages. We must add methods that are useful for manipulating the data of the class. Methods
are declared in the body of the class immediately after declaration of instance variables.
Syntax: type methodname (parameter list)
{
body of the method;
}
The method has four basic parts: they are
1. The name of the method (method name) (It is any valid identifier)
2. The type of the value the method return (type) (it is any valid data type, it is void when it does
not return any value.)
3. A list of parameters (parameter list) ( This list contains variable names and types of all the
values we want to send as input, when no input data are required, we must use empty
parentheses)
4. The body of the method: It describes the operations to be performed on the data.
Creating Objects: An object is a block of memory that contains space to store all the instance
variables. Java has an operator new to create objects. Creating an object is also referred to as
instantiating an object.
Ex: triangle tri1; ( declaring the object)
Tri1 = new triangle (instantiating the object)
The above two statements are combined into a single statement as
Triangle tri1 = new triangle();
We may create any number of objects of triangle.
Ex. Triangle tri1 = new triangle( );
Triangle tri2 = new triangle( );
Accessing class Members: every object contains its own set of variables. We should assign
values to these variables in order to use them in our program. When we are outside the class we
cannot access the instance variables and methods directly. For this we use dot operator.
Sy: objectname.varaiblename = value;
objectname.methodname(parameter list);
Ex: tri1.length = 15;
tri2.length = 20;
tri1.getData( 20,30)

Unit II 8
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Ex: A java program to demonstrate application of classes, objects and methods.
class triangle
{
int length, width; Instance variables declared in a single line
void getData(int x, int y) getData is a method, it does not return any
{ value so its type is void, we are passing two
length = x; integer values and they are assigned to
width = y; length and width
}
int triarea( ) triarea is another method, it returns a
{ value of data type int. We are not
int area = (length * width)/2 ; passing values, so the parameter list
return (area); is empty
}
}
class triarea class with main method
{
public static void main (String args[ ])
{
int area1, area2;
triangle tri1 = new triangle(); Creating objects
triangle tri2 = new triangle();
tri1.length = 20; Accessing variables
tri1.width = 30;
area1 =( tri1.length * tri1.width)/2;
tri2.getData( 10, 15); Accessing Methods
area2 = tri2.triarea();
System.out.println( "area1 = " + area1);
System.out.println( "area2 = " + area2);
}
}
Constructors: Constructor is a method that have same name as the class, it enables an object to
initialize itself when it is created. Constructors do not specify a return type, not even void also.
Constructors are two types they are parameterized constructors and default constructors.
A parameterized constructor is explicitly invoked by passing certain arguments, at the time of
object initialization where as default constructor is used to initialize the object variables with some
default values at the time of object initialization, so it does not take any parametric values.
Ex: triangle tri1 = new triangle(15,20) parameterized constructor
triangle tri1 = new triangle( ) default constructor
A program to demonstrate Parameterized and default constructors.

class area a=(length * width)/2;


{ System.out.println("\nArea = " + a);
int length ,width; }
area() }
{ class constructors
length=0; {
width=0; public static void main(String args[ ])
} {
area(int x, int y) area a1 = new area();
{ area a2 = new area(15,20);
length = x; a1.triarea();
width = y; a2.triarea();
} }
void triarea() }
{
int a;
Unit II 9
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)

Methods overloading: Java allows the user to create methods with same name in a class, but with
different parameter lists. This is called “method overloading”. It is used when we want to perform
similar tasks using different parameters. When we call that method based on the number and type of
the parameters it decides the method to execute. This feature is also called “polymorphism”. For this
we have to create several methods with same name and with different number of or type of
parameters in a class. Here the methods return type does not play any role.
Ex A program to demonstrate methods overloading.

class place return(length*breadth);


{ }
float length, breadth; }
place(float x, float y) class overloading
{ {
length=x; public static void main(String args[ ])
breadth=y; {
} float a1,a2;
place(float x) place area1 = new place(20.5f,15.5f);
{ place area2 = new place(20.5f);
length=breadth=x; System.out.println("Area of rectangular room is" + area1.area());
} System.out.println("Area of square room is " +area2.area());
float area() }
{ }

Static Members: A class declares variables and methods. These are called instance variables and
methods. These are associated with objects, when we instantiated a class a new copy of each of
them is created. If we want a member that is common to all objects and accessed without using a
particular object, we have to use Static Members. These are declared using a keyword “static”.
Ex: static int total;
static int max( int x, int y)
Static variables are called with out using objects. They are also used by other classes.
Suppose float x= Math.sqrt(25.0); here sqrt is a static method of Math class. Static methods are
called using class names. They have some restrictions:
1. They can only call other static methods.
2. They can only access static data.
3. They cannot refer to this or super in any way.
Ex:Program tt demonistrate Static Members.
class methods
{
static int add( int x, int y)
{
return x+y;
}
static int substract(int x, int y)
{
return x-y;
}
}
class staticmethods
{
public static void main(String args[ ])
{
int a = methods.add(20,30);
int b = methods.substract(a,25);
System.out.println("b = "+b);
}
}

Unit II 10
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Nesting of Methods: A method of a class can be called by an object of that class, in case of static
methods by class itself using dot operator. A method can be called by using only its name by another
method of the same class, this is known as nesting of methods.
Ex: A program to demonstrate nesting of methods.
class nesting
{
int a, b;
nesting( int x, int y)
{
a=x;
b=y;
}
int largest()
{
return((a>b)?a:b);
}
void display()
{
int large = largest() ;
System.out.println( "Largest value = " + large);
}
}
class nestmethod
{
public static void main(String args[])
{
nesting nest = new nesting(20,30);
nest.displ ay();
}
}
Inheritance: Reusability is an important aspect of the Object Oriented Programming. This is nothing
but reusing already existing concepts instead of creating again. Java supports this feature. We can
reuse a class by creating new classes. The mechanism of deriving a new class form already existing
class is called “inheritance”. The old class is known as super class or parent class, the new one is
known as derived, child or child class. The inheritance allows the subclasses to inherit all the
variables and methods of parent class. It has different forms; A

A A A B
B

B B C D
C
C
Single Inheritance Hierarchical Inheritance Multiple Inheritance
(Only one super (One super class, many Multilevel Inheritance (Derived
(Several Super classes)
class) subclasses from Derived classes)

Defining a sub class and subclass constructor:


A sub class in defined using keyword “extends”. It is used to extend the properties of super
class to sub class. The sub class contains all the variables and methods of super class and we may
add some own properties also. This is called single inheritance.
Ex: class abc extends xyz
Here xyz is the super class we are extending the properties of xyz to new sub class abc.
When we define a constructor in any sub class that is called “subclass constructor”. It is used
to construct both the variables of sub and super classes. It uses a keyword “super” to invoke the
method of super class. “super” is used only in subclass constructor. The parameters of super call
must match the order and type of variables declared in super class. Super call must be the first
statement in the subclass constructor.
Unit II 11
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Ex: A program to demonstrate single inheritance, sub class, super class and subclass constructor.
class hall height = z;
{ }
int length, breadth; int volume()
hall(int x, int y) {
{ return (length * breadth * height);
length = x; }
breadth = y; }
} class hallarea
int area() {
{ public static void main(String args[])
return(length*breadth); {
} mainhall h1= new mainhall(20,15,25);
} int area1= h1.area();
class mainhall extends hall int volume1=h1.volume();
{ System.out.println("Area of the hall = "+area1);
int height; System.out.println("Voluem of the hall = "+volume1);
mainhall(int x, int y, int z) }
{ }
super(x,y);

Overriding Methods: A method of super class is inherited by subclass and used by the objects
created by subclass. Java allows the user to create a method in sub class with same name as in the
super class with same arguments and same return type. This is called Methods overriding. This is
useful to perform different behaviors when it is called. When it is called with the object of the
subclass the method in the subclass will be invoked, when we call it with object of super class the
method of the super class is invoked.
Ex: Program to demonstrate overriding methods.
class super1 this.s2=y;
{ }
int s1; void display()
super1( int x) {
{ System.out.println(" super s1 ="+s1);
this.s1=x; System.out.println(" sub s2 ="+s2);
} }
void display() }
{ class subtest
System.out.println(" super s1 ="+s1); {
} public static void main(String args[ ])
} {
class sub1 extends super1 sub1 su1=new sub1(10,20);
{ super1 sup1=new super1(100);
int s2; su1.display();
sub1( int x, int y) sup1.display();
{ }
super(x); }

Final variables, methods and classes: All the methods and variables of super class are overridden
in subclasses. If we want to prevent the subclasses from overriding the members of super class we
can declare them as final using the keyword “final”. The final methods and variables are not allowed
to define in subclasses.
Ex: final int TOTAL = 100; (Final variable)
final void abc() (Final method)
We may prevent a class being further subclasses for some reasons. A class that cannot be
sub classed is called final class. This is possible by using the keyword “final”.
Ex: final class abc extends xyz
The class abc is not used as super class for any other class.

Unit II 12
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Abstract Methods and Classes: The keyword final prevents the methods and classes to overridden
in sub classes. Java supports a method exactly opposite to this, that is to make it must to redefine in
a subclass that means making overriding compulsory. This is possible by using the keyword
“abstract” in method definition.
Ex: abstract class cdc
{
::::::::::::::::::::::
abstract void teaching();
:::::::::::::::::::::
}
When any class contains abstract method or methods it must be declared as abstract; there are
some restrictions for abstract classes;
1. We cannot use abstract classes to instantiate objects directly.
2. The abstract method of an abstract class must be defined in its subclass.
3. We cannot declare abstract constructors and abstract static methods.

Visibility Control: We may inherit all the members of a class by subclass using keyword “extends”.
Some times we need to access members of a class everywhere in the program, in some other cases
we have to restrict certain members to access form out side of the class. All these things are
possible using “visibility modifiers” or “access modifiers”. Java provides three types of visibility
modifiers like “public, private and protected”.
Public Access: Public access is used to visible or access any variable or method to visible or
access everywhere in the program. It is possible by using key word “public” before the variable or
method while defining:
Ex: public int x;
public int sum(int x, int y)
Friendly Access: This is the default access modifier. When we do not use any access modifier then
by default it takes friendly access. This modifier is used to access the variable or method everywhere
it the package in which it is defined.
Protected Access: Protected access is used to access the variables or methods visible everywhere
in the same package in which it is defined and also in the subclasses of other packages. Non
subclasses of other packages cannot access protected members.
Ex: protected int x;
Private Access: Private access is used to access the variable or methods to access in their own
class. We can not inherit by subclasses, so we cannot use in subclasses. We can not over ride
private members.
Ex: private int x:
Private protected access: We may declare a member as “private protected”. This is used to
access the member in all subclasses in all packages. This is accessed in its own class and all the
subclasses of all the packages. But it is not accessed in other classes in the same package and non
sub classes in the other packages.
Ex: private protected int x;

Accessibility of member using various access/visibility modifiers:


Access Modifier Visibility / Accessibility
public Visible everywhere in the program
friendly(default) Visible everywhere in the current package.
protected Visible everywhere in the current package and sub classes in other packages
private Visible only in the class in which it is defined
private protected Visible in its own class and all the sub class of all the packages

Unit II 13

You might also like