Oops Notes
Oops Notes
y)
return x; [| ———+ body of the method
else
How to call a Jaya Method?
Now we defined a method, we need to use it. For that, we have to call the method. Here's how:
myMethod();
This statement calls the myMethod() method that was declared earlier.
class Main {
public static void main(string[] args) {
myFunction() 5
, e
private static void myFunction() {y [True if x is greater than y, otherwise false
(greater than or equal to) €x.x>=y [True if x is greater than or equal to y, otherwise false
less than or equal fo) ex. x= [True if x is less than or equal to y, otherwise false
Example
// Java peogzam to illustrate
// relational operators
public class operators
publi®static voidmain(string[] args)
(
ar(]
int br
boolean condition = trues
//various conditional operators
System.out-printin("a == b :"+ (a
Dds
Department of Computer Science and Engineering 58RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
System.out.printin("a b (a> dpe
System.out.printin("a >= b i" + (a >= b));
System-out-printin("a != b:"+ (a != b));
// exays cannot be compared with
Z/ relational operators because objects
7/ store references not the value
System.out.printin("x == yi "+ (ar
ve
System.out .printIn("condition~=true :"+ (condition ~~ true);
5. Logical Operators :
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function
ilar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, ic. it has short-circuiting effect. Used
extensively to test. for several conditions for making a decision.
Conditional operators are-
+ && Logical AND : returns true when both conditions are true.
al Logical OR : returns true if at least one condition is true.
// Java program to illustrate
// logical operators
public class operators
{
public static voidmain(string[] args)
{
string x
String y
Sher";
Locked";
Scanner s = new Scanner (System. in);
System-out print ("Enter usernam
String uvid next ()¢
Department of Computer Science and Engineering 38RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
System.out.print ("Enter password:");
String upwd = s.next ();
// Check if user-name and password match or not.
if ((uuid.equals(x) 6% upwd.equals(y)) |
(uuid-equals(y) && upwd.equals(x))) {
System-out.println("Welcome user.
} else (
System.out.printin("Wrong uid or password");
}
)
Output :
Enter username: Sher
Enter password: Locked
Welcome user
6. Ternary operator :
Temary operator is a shorthand version of if-else statement, It has three operands and hence the
name ternary. General format is-
condition ? if true : if false
Example
minval = (a >> Unsigned Right shift operator: shifts the bits of the number to the right and fills O
on voids left as a result. The leftmost bit is set to 0.
// sbitt operators
public class operators
public static void main(String[] args)
U/ left shift operator
77 0000 0101> 2.0000 0001 (1)
J) similar to 5/(2*2)
System.out .printin(a>>2 = "+ (a >> 2));
// unsigned eight shift operator
System.out.printla("b>>>2 = "+ (b >>> 2));
b>>>2 = 1073741821
Operator Precedence
Operator precedence determines the grouping of terms in an expression, This affects how an
expression is evaluated. Precedence and associative rules are used when dealing with hybrid
equations involving more than one type of operator. In such cases, these rules determine which
part of equation to consider first as there can be many different valuations for the same equation.
Department of Computer Science and Engineering aRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206,
Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator
Example
X=7+3* 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so
it first gets multiplied with 3 * 2 and then adds into 7
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Asso
Postfix >() [] . (dot operator) Left toright
Unary ee Right to left
Multiplicative 7 Left to right
Additive St Left to right
Shift So Left to right
Relational SS Left to right
Equality Left to right
Bitwise AND Left to right
Bitwise XOR Left to right
Bitwise OR Left to right
Logical AND Left to right
Logical OR Left to right
Conditional Right to left
‘Assignment Right to left
1.17 Control Flow Statements
When we write a program, we type statements into a file. Without control flow
statements, the interpreter executes these statements in the order they appear in the file from left
to right, top to bottom. We can use control flow statements in the programs to conditionally
execute statements, to repeatedly execute a block of statements, and to otherwise change the
normal, sequential flow of control.
The Java programming language provides several control flow statements, which are listed in the
following table.
Department of Computer Science and Engineering 68RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206,
Statement Type Keyword
decision making if-else, switch-case
while, do-while , for
Looping
exception handling try-catch-finally, throw
branching break, continue, labels,
117.1 Decision Making Statements,
Decision making statement statements is also called selection statement, That is depending on
the condition block need to be executed or not while is decided by condition. If the condition is
"true" statement block will be executed, if condition is “false” then statement block will not be
executed.
In java there are three types of decision making statement.
at
© ifelse
© switeh
it{ con
If condition
condition
is false
Department of Computer Science and EngineeringRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
iffthen Statement
if-then is the most basic statement of the decision making statement. It tells to program to
execute a certain part of code only if a particular condition or testis true,
Statement (5)
‘© Constructing the body if always optional, that is recommended to create the body when
we are having multiple statements.
‘© Fora single statement, itis not required to specify the body.
© Ifthe body is not specified, then automatically condition parts will be terminated with
next semicolon ;.
+ Itis a keyword, by using this keyword we can ereate an alternative block for "if" part.
‘+ Using else is always optional i.e, itis recommended to use when we are having alternate
block of condition.
‘+ When we are working with if else among those two block at any given point of time only
‘one block will be executed
‘+ When if condition is false, then else part will be executed, if partis executed, then
automatically else part will be ignored.
if-else statement
In general, it can be used to execute one block of statement among two blocks, in Java language
if and else are the keyword in Java.
Syntax
{e(conaition)
statement (8)
st
tement (s)
Statement (9)
Department of Computer Science and Engineering 65RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206,
In the above syntax whenever the condition is true all the if block statement are executed
remaining statement of the program by neglecting else block statement. If the condition is false
else block statement remaining statement of the program are executed by neglecting if block
statements.
A Java program to find the addition of two numbers if first number is greater than the second.
number otherwise find the subtraction of two numbers.
Example
import java.util.*;
clase Nan
(
public static void main(String args|])
a-10,b=20, 7
System.out.printIn ("Enter any two num");
5£ (a>)
cxa-b;
System. out .printin ("Result:
3. Switch Statement
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax
switch (expres
ion/variable)
i
case value:
Jiscaxenents
7] any number of case statements
br@ak: \//optional
@efaule: //optional
/Iecatenents
Rules for apply switch statement
With switch statement use only byte, short, int, char data type. We can use any number of case
statements within a switch. The value for a case must be same as the variable in a switch.
Limitations of switch statement
Logical operators cannot be used with a switch statement. For instance
Department of Computer Science and Engineering 66RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
Example
case k>~2i
is not allowed
Switch case variables can have only int and char data type. So float data type is not allowed, For
instance in the switch syntax given below:
break;
In this ch can be integer or char and cannot be float or any other data type.
1.17.2 Looping statement
These are the statements execute one or more statement repeatedly a several number of times. In
Java programming language there are three types of loops are available, that is, while, for and
do-while.
Advantage with looping statement
‘+ Length on the developer is reducing.
‘+ Burden on the developer is reducing.
‘+ Burden of memory space is reduced time consuming process to execute the program is,
reduced.
Difference between conditional and looping statement
Conditional statement executes only once in the program were as looping statement executes
repeatedly several numbers of time.
1, While loop
‘+ When we are working with while loop always pre-checking process will be occurred.
‘+ Pre-checking process means before the evolution of statement block condition parts will
be executed,
Department of Computer Science and Engineering orRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
‘+ While loop will be repeated in clockwise direction,
Syntax
while (condition)
G
ment (3)
rement / decrements (++ or
D
Example
class whilepeno
q
public static void main(String args (J)
int 1-0;
while (i has been used for creating paragraph
break.
Example
pe
*
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
* @author Author_Name
* @version 1.0
*@since 2018-03-31
g
public class HelloWorld {
public static void main(String{] args) {
/* Prints Hello, World! on standard output.
Department of Computer Science and Engineering 85RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
System.out printin("Hello World!");
+
+
1.20.1 The javadoe Tags
The javadoc tool recognizes the following tags
should no longer be used.
Tag Description Syntax
@author Adds the author of a class. @author name-text
Displays text in code font without
{@eode} interpreting the text as HTML markup or {@code text}
nested javadoc tags.
Represents the relative path to the generated
{@docRoot} | document's root directory from any generated | {@docRoot}
page,
@deprecatea | Adds @ comment indicating that this APL @deprecated deprecatedtext
@exception
Adds a Throws subheading to the generated
documentation, with the classname and
description text.
@exception class-name
description
{@inheritDoc
3
Inherits a comment from
the nearestinheritable class or implementable
interface.
Inherits a comment from the
immediate surperclass
Inserts an in-line link with the visible text
label that points to the documentation for the
{@link
description to the "Parameters" section.
{@linky specified package, cass, or member name of | P&tkege.classi#member
label}
areferenced class.
Identical to {@link}, except the link’s label is | {@linkplain
{@linkplain} | displayed in plain text than code font. package.classi#member
label}
Adds a parameter with the specified a
@param parameter-name followed by the specified param pal
description
Department of Computer Science and Engineering 86RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
Adds a "Returns" section with the description
@return ae @retum description
Adds a "See Also" heading with a link or text |
Ce entry that points to reference. selene
@seriat Used in the doc comment for a default @serial field-description |
serializable field.
include | exclude
@serialData
Documents the data written by the
writeObject( ) or writeExtemal( ) methods.
@serialData data-
description
Documents an ObjectStreamField
@serialField field-name
QserialField | component. field-type field-description
‘Adds a "Since" heading with the specified
@since since-text to the generated documentation, | @since release
Pe The @throws and @exception tags are @throws class-name
synonyms. description
When (@value} is used inthe oe comment | vay
{@value} | of astatc fied, it displays the value ofthat] T@valwe |
oe package class#ield}
‘Adds a "Version" subheading with the
ified version-text to the generated d
@version —_| SHecifird versionvtext io the generated docs | @version version-text
when the -version option is used.
© End of Unit — 1 ***
Department of Computer Science and Engineering 87RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
UNIT — I - INHERITANCE AND INTERFACES
2.1 Inheritance
An important part of OPPs(Object Oriented programming system) is Inheritance.
The process by which one class acquires the properties(data members) and
functionatities(methods) of another class is called inheritance. The keyword used inherit the
propertied of a class is extends.
The idea behind inheritance in java is that we can create new classes that are built upon
existing classes. When we inherit from an existing class, we can reuse methods and fields of
parent class, and we can add new methods and fields also.
Syntax
class subClass extends superClass
{
/imethods and fields
+
Tert
ology
Super Class (Parent Class) : The class whose features are inherited is known as super
class(or a base class or a parent class).
‘Sub Class (Child Class): The class that inherits the other class is known as sub class(or
a derived class, extended class, or child class). The subelass can
add its own fields and methods in addition to the superclass
fields and methods
Reusability : Inheritance supports the concept of “reusability”, ie. when we
want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the
fields and methods of the existing class.
Example:
In below example of inheritance, class Bicycle is a base class, class MountainBike is a
derived class which extends Bicycle class and class Test is a driver class to run program.
//Java program to illustrate the concept of inheritance
// base class
class Bicycle
i
// the Bicycle class has two fields
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
public int gear,
public int speeds
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this. speed = speed;
,
// the Bicycle class has three methods
public void applyBrake (int decrement)
fl
speed -= decrement;
,
public void speedup (int increment)
cl
speed ++ increment;
,
// toString() method to print info.of Bicycle
public String toString()
cl
return("No of gears are."+gear
+"\n"
+ "speed of bicycle) isu"+speed) +
}
// derived class
class NcuntainBike extends Bicycle
(
// the HountainBike Subclass adds one more field
publi¢int seatHeight;
/{ the\MountainBike subclass has one constructor
publicMountainBike(int gear, int speed, int startHeight)
cl
/} invoking base-class (Bicycle) constructor
super (cear, speed);
seatHeight = startHeights
,
// the MountainBike subclass adds one more method
public void setHeight (int newValue)
cl
seatHeight = newValue;
,
// overriding toString() method of Bicycle to print more info
Goverride
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
public String toString ()
‘ return (super.toString()+"\nseat height is "+seatHeight);
,
I
// driver class
public class Test
(
public static voidmain(string args{])
(
MountainBike mb = newMountainBike(3, 100, 25);
System. out .print1n (mb. toString ());
b
Output:
No of gears are 3
speed of bicycle is 100
Seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and
fields of the superclass acquire memory in this object. That is why, by using the object of the subclass
‘we can also access the members of a superclass.
Iustrative image of the prograr
int gear
int speed copy of Bicycle methods and
applyBrake()| fields in MountainBike object
speedUp()
toString()
objects of MountainBike class
int seatHeight
setHeight()
toString()
‘The super keyword
‘The super keyword is similar to this keyword. Following are the scenarios where
the super keyword is used.
‘+ It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
+ It is used to invoke the superclass constructor from subclass.RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
Important faets about inheritance in Java
Default superclass: Except Object class, which has no superclass, every class has one and only
one direct superclass (s
gle inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class,
Superclass can only be one: A superclass can have any number of subclasses, But a subclass can
have only one superclass. This is because Java does not support multiple
inheritance with classes
Although with interfaces, multiple inheritance is
supported by java.
Inheriting Constructo
A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked
from the subclass,
A subelass does not inherit the private members of its parent class.
However, if the superclass has public or protected methods(like getters and
setters) for ack
ing its private fields, these can also be used by the subclass.
Role of Subclass
In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new
‘members:
‘+ The inherited fields can be used directly, just like any other fields.
‘* Wecan declare new fields in the subclass that are not in the superclass
‘© The inherited methods can be used directly as they are.
We can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it (as in example above, toString() method is overridden),
‘*) Weccan write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it
© We can declare new methods in the subclass that are not in the superclass.
© We can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
2.1.1 Types of Inheritance
884 (Please refer UNIT Notes for detailed explanation and examples)
Single Inheritance public lass A ¢
Class A z
}
public lass B extends A {
Class 8 }
‘Maiti Level taheritance
public class A ( )
public class B extends A {....
public dass C extends B {econo}
iorarchical inheritance
public dass A )
puble dass B extends A... }
[tase c | | puttecass Coxtands A (ob
‘Maltiple Inheritance public dass A )
public class B ,
Se public class C extends A,8 {
11 Java does not support mutiple Inheritance
2.1.2 Super Class
The super keyword in java is a reference variable which is used to refer immediate parent
class object. Whenever we create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer émmediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor
1) super is used to refer immediate parent class instance variable..
Department of Computer Science and EngineeringRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
Example
class Animal{
String color="white";
+
class Dog extends Animal{
String color="black"
void printColor()
class Dog extends Animal{
Dog(){
‘System.out.printin("dog is created");
+
+
class TestSupera{
public static v
main(String args[]){
Department of Computer Science and EngineeringRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
Dog
oo
yew Dog);
Output
animal ie created
dog is created
2.1.3 Protected Member
The private members of a class cannot be directly accessed outside the class. Only
methods of that class can access the private members directly. However, sometimes it may be
necessary for a subclass to access a private member of a superclass. If we make a private
member public, then anyone can access that member. So, if'a member of a superclass needs
to be (directly) accessed in a subclass and yet still prevent its direct access outside the class,
you must declare that member protected.
Following table deseribes the difference
Modifier Class Subclass World
public Y Y Y
protected ¥ Y N
private ¥ N. N
Following program illustrates how the methods of a subclass can directly access a protected
‘member of the superclass.
For example, le’s imagine a series of classes to
describe two kinds of shapes: rectangles and
triangles. These two shapes have certain common
properties height and a width (or base).
This could be represented in the world of classes
with a class Shapes from which we would derive
the two other ones : Rectangle and Triangle
Example
Department of Computer Science and EngineeringRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
public class shape
{
protected double height; // To hold height.
protected double width; //To hold width or base
* The setValue method sets the data
* in the height and width field
public void setValues(double height, double width:
this.height = height;
this.width = width;
Rectan;
ye
* This class Rectangle calculates
* the area of rectangle
*
public class Rectangle extend# Shape
t
yee
* The method retufns the area
* of rectangle.
*/
public double getarea ()
(
return height * width; //accessing protected members
}
Triangle.java
ye
* this class Triangle calculates
* the area of triangle
y
public class Triangle extends Shape
{
yee
* The method returns the area
* of triangle.
*/
public double getarea()
ci
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
return height * width / 2; //accessing protected members
‘Testprogram,java
Jan
* This program demonstrates the Rectangle and
* ‘riangle class, which inherits from the Shape class.
“/
public class TestProgram
(
public static void main(String[] args)
fl
{/Create object of Rectangle.
Rectangle rectangle = new Rectangle();
{/Create object of Triangle
Triangle triangle = new Triangle();
(Set values in rectangle object
rectangle.setValues (5,4);
//Set values dn trianlge object
triangle.setValues (5,10);
// Display the/area Of rectangle.
System.out.printin ("Area of rectangle : " +
rectangle.getArea()) 7
//-pisplay the’area of triangle.
System.out.print1n("Area of triangle : " +
triangle.getArea());
Output :
Area of rectangle : 20.0
Area of triangle : 25.0
2.1.4 Constructors in sub classes
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
In Java, constructor of base class with no argument (default constructor) gets automatically
called in derived class constructor. For example, output of following program is:
Example
Main. java
Base()
System.out.println ("Base Class Constructor Called ");
}
class Derived extends Base (
Derived()
System. out.printin ("Derived Class Constructor Called ")
}
publicclass Main {
public static voidmain(String[] args) {
Derived d = new Derived():
t
output
Base Class Constructor Called
Derived Class Constructor Called
But, if we want to call parameterized contructor of base ela
, then we can call it using
ss constructor call must be the first line in derived class
super(). The point to note is base
constructor. For example, in the following program, super(_x) is first line derived class
constructor.
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
// filename: Main. java
class Base {
int x:
Base(int_x) {
}
class Derived extends Base {
int yz
Derived(int x, int_y) {
uper (_x)7
Wi
void Display() {
System.out.println("* = "+x", y =
}
publicclass Main {
public static void main(String[] args)\ {
Derived d = new Derived(10, 20);
d.Display();
}
Run on IDE
Output:
x= 10,y=20
The rules is: sub class constructor has to invoke super class instructor, either explicitly by
programmer or implicitly by compiler. For either way, the invoked super constructor has to be
defined.
2.1.5 The Object Class
Every class in Java is directly or indirectly derived from the Object class. All other classes are
subelasses of Object. The Object class is the parent class of all the classes in java by default.
In other words, it is the topmost class of java. That is, Object is a superclass of all other
classes. This Means that a reference variable of type Object can refer to an object of any other
class. Also, since arrays are implemented as classes, a variable of type Object can also refer
to any array. Object defines the following methods, which means that they are available in
every object.
Note : The Object class, in the java.lang package, sits at the top of the class hierarchy tree
Method Purpose
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
‘Creates a new object that is the same as the
object being cloned.
‘Determines whether one object is equal to
Object clone( )
boolean equals(Object object)
another.
void finalize ) Called before an unused object is recycled.
Class getClass( ) Obtains the class of an object at run time
Returns the hash code associated with the
invoking object.
Resumes execution of a thread waiting on
the invoking object.
Resumes execution of all threads waiting on
the invoking object.
int hashCode( )
void notify)
void notifyA()
String toString() Returns a string that describes the object.
void wait()
void wait(long milliseconds)
void wait(long milliseconds,
int nanoseconds)
Waits on another thread of execution,
‘The methods getClass( ), notify( ), notifyAII( ), and wait( ) are declared as final, You may
override the others.
2.1.6 Abstract Classes
There are situations in which we will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method. That is, sometimes we will want to create a superclass that only defines a
generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill
in the details. Such a class determines the nature of the methods that the subclasses must
implement. One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
General form:
abstract type name (parameter-list);
To declare a class abstract, we simply use the abstract keyword in front of the elass keyword
at the beginning of the class declaration.
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
Here is a simple example of a class with an abstract method, followed by a class which
implements that method:
// ® Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.printin("This is a concrete method."
}
}
class B extends A {
void calime() {
System.out.printin("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(string args(]) {
Bb = new B(
b.callme(
b.callmetoo() +
y
,
Notice that no objects of class A are declared in the program. As mentioned, it is not
possible to instantiate an abstract class. One other point: class A implements a concrete
‘method called eallmetoo( ).
Although abstract elasses cannot be used to instantiate objects, they can be used to
create object references, because Java’s approach to run-time polymorphism is implemented
through the use of superclass references. Thus, it must be possible to create a reference to an
abstract class so that it can be used to point to a subel
38 object.
Using an abstract class, we can improve the Figure class example. Since there is no
‘meaningful concept of area for an undefined two-dimensional figure, the following program
declares area( ) as abstract inside Figure. This, of course, means that all classes derived from
Figure must override area( ).
// Using abstract methods and classes.
abstract class Figure [
double dim;
double din2;
Figure(double a, double b) {
dim = a;
dim? = b;
)
// area is now an abstract method
abstract double area();
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
,
class Rectangle extends Figure {
Rectangle (double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.printin ("Inside Area for Rectangle.");
return dim] * dim2;
}
}
class Triangle extends Figure {
Triangle (double a, double b) {
super (a, b);
}
// override area for right triangle
double area) {
System.out.printin ("Inside Area for Triangle.
return diml * dim2 / 2;
}
}
class Abstractareas {
public static void main(String args (J)
// Figure £ = new Figure(10, 10)%// illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref =
system.out .printin ("Area ia." + figref.area());
figref = t;
system.out.p
}
}
ntin ("area is “ + figref.area());
As the comment inside main( ) indicates, it is no longer possible to declare objects of
type Figure, since it is now abstraet, And, all subclasses of Figure class must override area()
Although it is not possible to create an object of type Figure, we can create a reference
variable of type Figure. The variable figref is declared as a reference to Figure class, which
‘means that it can be used to refer to an object of any class derived from Figure class.
2.1.7 Final Methods and Classes
Inheritance is one of the highly useful features in Java, But at times, it may be desired
that a class should not be extendable by other classes to prevent misusing by others. For such
purpose, we have the final keyword. A class declared as final cannot be extended while a
Department of Computer Science and Enginee!RMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
method declared as final cannot be overridden in its subclasses. Though a final class cannot
be extended, it can extend other classes. /n simpler words, a final class can be a sub class but
not a super class.
Normally, Java resolves calls to methods dynamically, at run time. This is called fate
binding. However, since final methods cannot be overridden, a call to one can be resolved at
compile time. This is called early binding.
Syntax
final public class A
//code
}
The final keyword can be placed either before or after the access specifier. The following
deck
jon of class A is equivalent to the above.
public final class A
//code
,
final keyword is used in different contexts. First of all, final is a non-access modifier
applicable only to a
© variable,
© amethod
© aclass.
Final Variable:
If we make any variable as final, we cannot change the value of final variable (It will be
constant).
Example of final variable
‘There is a final variable speedlimit, we are going to change the value of this variable, but it
can't be changed because final variable once assigned a value can never be changed
class Bike{
al int speediimit=90; //final variable
void run(){
speedlimit=400;
+
public static void main(String args(])
¥
Output
Hello
Nested Interfaces
Department of Computer Science and EngineeringRMK College of Engineering and Technology
RSM Nagar, Puduvoyal-601 206.
An interface can be declared a member of a class or another interface. Such an interface is
called a member interface or a nested interface.
Example
// & nested interface example.
// This class contains a member interface.
class A {
// this is a nested interface
public inte: ice NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x
Here, E speci
Declaration
the type of objects that the list will hold.
public class ArrayListHello, World!
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
*