Dsa Pyqs
Dsa Pyqs
The major objective of object-oriented approach is to eliminate some of the flaws that are there
in the procedural programming. OOP treats data as a critical element in the program
development and does not allow it to flow freely around the system It ties data more closely to
the functions that operate on it and protects it from unintentional modification by other
functions. OOP allows us to decompose a problem into several entities called Objects and then
build data and functions (known as methods in Java) around these entities. The combination of
data and methods make up an object.
Objects
1
Objects are the basic runtime entities in an object-oriented system. They may represent a person,
a place, a bank account, a table of data or any item that the program may handle. They may also
represent user-defined data types such as vectors and lists. Any programming problem is
analyzed in terms of objects and the nature of communication between them. An object takes
up space in the memory and has an associated address. When a program is executed, the objects
interact by sending messages to one another. Each object contains data and code to manipulate
the data, Objects can interact without having to know the details of each other's data or code. It
is sufficient to know the type of message accepted and the type of response returned by the
objects.
Classes
The entire set of data and code of an object can be made a user-defined data type using the
concept of a class. A class may be thought of as a ‘data type’ and an object as a ‘variable’ of
that data type. Once a class has been defined, we can create any number of objects belonging to
that class, each object is associated with the data of type class with which they are created.
A class is thus a collection of objects of similar type.
Principles of OOP:
i. Data Abstraction
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces
Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and methods that operate on these attributes, they
encapsulate all the essential properties of the objects that are to be created.
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
ii. Encapsulation
The wrapping up of data and methods into a single unit (called class) is known as encapsulation.
The data is not accessible to the outside world and only those methods, which are wrapped in
the class, can access it. This insulation of the data from direct access by the program is called
data hiding.
iii. Polymorphism
2
Polymorphism in Java is a concept by which we can perform a single action in different
ways .Polymorphism means the ability to take more than one form. For example, an operation
may exhibit different behaviour in different instances. The behaviour depends upon the types
of data used in the operation. Polymorphism is extensively used in implementing inheritance.
iv. Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. The concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving
a new class (Sub class or derived class or child class) from the existing one (Base Class or Super
Class or Parent class). The new class will have the combined features of both the classes (Parent
and child class).
• Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
• It is possible to have multiple objects to coexist without any interference.
• It is possible to map objects in the problem domain to those objects in the program.
• It is easy to partition the work in a project based on objects,
• The data-centered design approach enables us to capture more details of a model in an
implementable form.
• Object-oriented systems can be easily upgraded from small to large systems.
• Message passing techniques for communication between objects make the interface
descriptions with external systems much simpler.
• Software complexity can be easily managed
3
Java programming fundamentals: history of java
Java, having been developed in 1991, is a relatively new programming language. At that time,
James Gosling from Sun Microsystems and his team began designing the first version of Java
aimed at programming home appliances which are controlled by a wide variety of computer
processors.
Why is it called Java? It is customary for the creator of a programming language to name the
language anything he/she chooses. The original name of this language was Oak, until it was
discovered that a programming language already existed that was named Oak. As the story
goes, after many hours of trying to come up with a new name, the development team went out
for coffee and the name Java was born.
While Java is viewed as a programming language to design applications for the Internet, it is a
general all-purpose language which can be used independent of the Internet. Java is related to
C++, which is a direct descendant of C. Much of the character of Java is inherited from these
two languages. From C, Java derives its syntax. Many of Java’s object-oriented features were
influenced by C++.
Java in order to support security and portability, does not compile the source code to executable
code. It is translated into bytecode, which is highly optimized set of instructions designed to be
executed by the Java run-time system, which is called Java Virtual Machine (JVM).
JVM is an interpreter of bytecode. Converting the Java program to bytecode instead of compiled
code, offers a great ability to run those programs on multiple platforms. Once we have the run-
time package for a given system, then any Java program can run on it. Instead, if Java programs
were to be compiled to the native code, then it would be very difficult since the same program
must be compiled for every CPU type. Using JVM also offers a protected environment which
helps in enhanced safety for the system. This reduces any side effects caused by the programs.
Java buzzwords
Simple: Java was designed to be easy for the professional programmer to learn and use
effectively. Because Java inherits the C/C++ syntax and many of the object-oriented features of
C++, most programmers have little trouble learning Java.
Secure: Java provides a “firewall” between a networked application and your computer. When
a Java Compatible Web browser is used, downloading can be done safely without fear of viral
infection or malicious intent. Java achieves this protection by confining a Java program to the
java execution environment and not allowing it to access other parts of the computer.
Portable: Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet. It helps in generating Portable executable code.
4
Object-oriented: Java is true object oriented language. Almost “Everything is an Object”
paradigm. All program code and data reside within objects and classes. The object model in
Java is simple and easy to extend. Java comes with an extensive set of classes, arranged in
packages that can be used in our programs through inheritance.
Robust: Java provides many features that make the program execute reliably in variety of
environments. Java is a strictly typed language. It checks code both at compile time and runtime.
Java takes care of all memory management problems with garbage-collection. Java, with the
help of exception handling captures all types of serious errors and eliminates any risk of
crashing the system.
High performance: Java performance is high because of the use of bytecode. The bytecode was
used, so that it was easily translated into native machine code.
Distributed: Java is designed for distributed environment of the Internet. Its used for creating
applications on networks. Java applications can access remote objects on Internet as easily as
they can do in local system. Java enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
Dynamic: Java can link in new class libraries, methods, and objects. It can also link native methods
(the functions written in other languages such as C and C++).
5
Data types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and Boolean.
• Integers This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
• Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
• Characters This group includes char, which represents symbols in a character set, like
letters and numbers. Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all the characters found in all human
languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic,
Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16
bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536
• Boolean Java has a primitive type, called boolean, for logical values. It can have only
one of two possible values, true or false.
6
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility.
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
1. Local variables
• Local variables are declared in methods, constructors, or blocks.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared, and
an initial value should be assigned before the first use.
2. Instance variables
• Instance variables are declared in a class, but outside a method, constructor or any
block.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors, and block in the class.
• Instance variables have default values. For numbers, the default value is 0, for Booleans
it is false, and for object references it is null. Values can be assigned during the
declaration or within the constructor.
3. Class/Static variables
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• Constants are variables that are declared as public/private, final, and static. Constant
variables never change from their initial value.
• Visibility is like instance variables. However, most static variables are declared public
since they must be available for users of the class.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the
class name ClassName.VariableName.
Arrays
An array is a collection of elements of same data type. Arrays of any type can be created and may
have one or more dimensions. A specific element in an array is accessed by its index.
One-Dimensional Arrays:
7
Instantiation of an Array in Java array_name=new
data_type[size];
Example
8
//Java Program to illustrate the use of multidimensional array
class MultiArrayDemo
{
public static void main(String args[])
{
//declaring and initializing 2D array int
arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
1.10. Operators
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical. Java also defines some
additional operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
9
Relational Operators
The relational operators determine the relationship that one operand has to the other. Specifically,
they determine equality and ordering.
Java supports two selection statements: if and switch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time.
if:
The if statement is Java’s conditional branch statement. It can be used to route program execution
through two different paths. Here is the general form of the if statement:
if (condition)
statement1;
else statement2;
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2
(if it exists) is executed.
Nested ifs:
if (condition)
{
if (condition)
statement3;
else
statement4;
}
else statement2;
The if-else-if Ladder:
11
Switch:
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression.
switch (expression)
{ case
value1:
// statement sequence break;
case value2:
// statement sequence break;
. . . case
valueN:
// statement sequence break;
default:
// default statement sequence }
Example
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i)
{ case
0:
System.out.println("i is zero."); break;
case 1:
System.out.println("i is one."); break;
case 2:
System.out.println("i is two."); break;
case 3:
12
System.out.println("i is three."); break;
default:
System.out.println("i is greater than 3."); }
}
}
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. A loop repeatedly executes the same set of instructions until a termination
condition is met.
While Loop:
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its
controlling expression is true. Here is its general form:
while(condition)
{
// body of loop }
do-while Loop:
The do-while loop al ways executes its body at least once, because its conditional expression is
at the bottom of the loop. Its general form is:
do {
// body of loop
} while (condition);
For Loop:
Beginning with JDK 5, there are two forms of the for loop. The first is the traditional form that
has been in use since the original version of Java. The second is the new “for-each” form.
The general form of the for-each version of the for is shown here:
13
The following fragment uses a traditional for loop to compute the sum of the values in an
array:
The for-each style for automates the preceding loop. Specifically, it eliminates the need to
establish a loop counter, specify a starting and ending value, and manually index the array.
Instead, it automatically cycles through the entire array, obtaining one element at a time, in
sequence, from beginning to end. For example, here is the preceding fragment rewritten using
a for-each version of the for:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; for(int x: nums)
sum += x;
Jump StatementsBreak
in Java
The break statement has three uses. First it terminates a statement sequence in a switch
statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of
goto.
Continue in java
Continue is useful to force an early iteration of a loop. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional expression that controls the
loop. In a for loop, control goes first to the iteration portion of the for statement and then to the
conditional expression. For all three loops, any intermediate code is bypassed.
return
The last control statement is return. The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the method.
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
When these two conditions are met, a widening conversion takes place.
For example, the int type is always large enough to hold all valid byte values, so no explicit cast
statement is required.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
int a; byte
b; // ... b =
(byte) a;
Concepts of classes
A class defines a new data type. Once defined, this new type can be used to create objects of that
type. Thus, a class is a template for an object, and an object is an instance of a class.
class classname {
// declare methods
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
15
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}
Example
• First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object. o Class_Name
Object_Name;
• Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator. o Object_Name = new
ClassName();
The new operator dynamically allocates (allocates at run time) memory for an object and
returns a reference to it. This reference is address in memory of the object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated.
16
Constructors
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called. It calls a default
constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
There are two types of constructors in Java: no-argument constructor, and parameterized
constructor.
17
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
18
s1.display();
s2.display();
}
}
1.16. Methods
A Java method is a collection of statements that are grouped together to perform an operation.
Creating Method:
// method body }
•
modifier − It defines the access type of the method and it is optional to use.
•
returnType − Method may return a value.
•
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
19
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
2) Method Overloading: changing data type of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Note:
• In java, method overloading is not possible by changing the return type of the method
only because of ambiguity.
• By method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.
Access control
Access modifiers in Java helps to restrict the scope of a class, constructor , variable , method
or data member. There are four types of access modifiers available in java:
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
• Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
20
• Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package
This keyword
This is a reference variable that refers to the current object. This is always a reference to the
object on which the method was invoked. This keyword may be used in following:
}
class TestThis2{ public static void
main(String args[])
{
Student s1=new Student(111,"abc",5000f);
Student s2=new Student(112,"xyz",6000f);
s1.display(); s2.display();
}
}
21
2) To invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method.
class A{ void
m()
{
System.out.println("hello m");
} void
n()
{
System.out.println("hello n"); //m();
//same as this.m()
this.m();
}
}
class TestThis4
{ public static void main(String args[])
{
A a=new A();
a.n();
}
}
3) To invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor.
class A
{
A()
{
System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}
22
Garbage Collection
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically.
• It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage collector (a part of JVM) so we do not need to
make extra efforts.
e=null;
3) By anonymous object:
new Employee();
finalize() method
By using finalization, you can define specific actions that will occur when an object is just
about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define
the finalize( ) method. The Java run time calls that method whenever it is about to recycle an
object of that class. Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed. The finalize( ) method has this general form:
It is important to understand that finalize( ) is only called just prior to garbage collection. It is
not called when an object goes out-of-scope, for example. This means that you cannot know
when—or even if—finalize( ) will be executed.
gc() method
23
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes. public static void gc(){}
The static keyword in Java is used for memory management mainly. When a member is
declared static, it can be accessed before any objects of its class are created, and without
reference to any object. You can declare both methods and variables to be static. The most
common example of a static member is main( ). main( ) is declared as static because it must be
called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of its class
are declared, no copy of a static variable is made. Instead, all instances of the class share the
same static variable.
Final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
• Variable: If you make any variable as final, you cannot change the value of final
variable(It will be constant). Example final float PI=3.14;
• Method: If you make any method as final, you cannot override it. Example: final type
method_Name()
• Class: If you make any class as final, you cannot extend it.
Example: final class Class_Name
It is possible to define a class within another class; such classes are known as nested classes.
There are two types of nested classes: static and non-static.
24
• A static nested class is one that has the static modifier applied. Because it is static, it
must access the members of its enclosing class through an object. That is, it cannot refer
to members of its enclosing class directly. Because of this restriction, static nested
classes are seldom used.
• The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of the outer class
do.
class InnerClassDemo
{ public static void main(String args[])
{
Outer outer = new Outer(); outer.test();
}}
1.23. Exploring the String Class
Every string you create is an object of type String. Even string constants are String objects.
Once a String object is created, its contents cannot be altered.
• The easiest is to create a string statement like this:
• Java defines one operator for String objects: +. It is used to concatenate two strings.
• You can test two strings for equality by using equals( ). boolean equals(String object)
class StringEqual
{ public static void main(String args[]){
String s1="Rasool";
String s2="Rasool";
25
System.out.println(s1.equals(s2));//true
}
}
• You can obtain the length of a string by calling the length( ) method.
int length( )
A command-line argument is the information that directly follows the program’s name on the
command line when it is executed. To access the command-line arguments inside a Java
program is quite easy— they are stored as strings in a String array passed to the args parameter
of main( ). The first command-line argument is stored at args[0], the second at args[1], etc.
>javac CommandLine.java
> java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
26
args[3]: test
args[4]: 100
args[5]: -1
1.25. Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours of a parent object. To inherit a class, you simply incorporate the definition of one
class into another by using the extends keyword. Inheritance in Java permits reusability of
code so that a class only needs to write the unique features and the rest of the code can be
extended from the other class.
Sub Class / Derived Class / Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
Super Class / Base Class / Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
syntax of Inheritance:
A class that extends only one class. In the following example, class apple extends class fruit.
i.e. Fruit is the superclass and Apple is the subclass that extends the properties and behaviour
of Fruit class.
27
//parent class class
fruit { public void
taste()
{
System.out.println("Fruits are sweet");
}
}
//child class of fruit
class apple extends fruit
{
public void shape()
{
System.out.println("Apple is round");
}
}
public class InheritanceExample
{
public static void main(String[] args) { apple
fr = new apple(); //object of child class
fr.taste(); //call method of parent class
fr.shape(); //call method of child class
}
}
ii. Multi-Level Inheritance
In this type of inheritance, a class will be extended from another class and the derived class act
as the base class for some other class.
For example, in the figure, a class four-wheeler is the parent class and the car is the derived
class of four-wheeler class. At the same time, the class car can be the base class for class Maruti.
28
//Java program to demonstrate Multiple Inheritance
//parent class
class fourwheeler {
public void wheels()
{
System.out.println("I have 4 wheels");
}
}
//child class of fourwheeler and parent of maruti
class car extends fourwheeler
{
public void type()
{
System.out.println("I'm a car");
}
}
//child class of car class
class maruti extends car
{
public void comp()
{
System.out.println("I'm maruti");
}
}
public class InheritanceExample
{
public static void main(String[] args) {
maruti fr = new maruti(); //object of child class
fr.wheels();
fr.type();
fr.comp();
}
}
3. Hierarchical Inheritance
In Hierarchical inheritance, a base class has more than one child class, which means the
properties of a class is acquired by different classes.
29
//Java program to demonstrate Hierarchical Inheritance
//parent class
class vehicle {
public void wheels()
{
System.out.println("I have wheels");
}
}
//first child class of vehicle class
class bike extends vehicle
{
public void countwl()
{
System.out.println("I am a bike and has 2 wheels");
}
}
//second child class of vehicle class
class car extends vehicle
{
public void countwlc()
{
System.out.println("I am a car and has 4 wheels");
}
}
//third child class of vehicle class
class scooter extends vehicle
{
public void countwls()
{
System.out.println("I am a scooter and has 2 wheels");
}
}
public class InheritanceExample
{
public static void main(String[] args) {
scooter sc = new scooter(); //object of scooter class
sc.wheels();
sc.countwls();
car c = new car(); //object of car class c.wheels();
c.countwlc(); bike b= new
bike();//object of bike class b.wheels();
b.countwl();
}
}
Multiple inheritance is not supported in java:
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
30
ambiguity to call the method of A or B class.
A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.
class Base
{
void Msg1()
{
System.out.print("Hello");
}
}
}
public class BaseClassRefernceVariableCanReferToADirivedClassObject
{
public static void main(String args[])
{
Base ref;
Dirived obj = new Dirived();
ref = obj;
ref.Msg1();
}
}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Super is a keyword in Java which is used to refer to the methods or functions, instance
variables or attributes and constructors in the parent class.
Example #1
In the following program, a common variable name is present and super is used to call the
variable in a parent class.
//Java program to illustrate Super keyword to refer instance variable
//parent class class
A{
protected String name="ann";
}
//child classs class
B extends A {
public String name="Anna";//variable which is same in parent class
//sample method public
void hello() {
System.out.println("I am " + name);
System.out.println("I am " + super.name);
}
}
//main class
public class SuperExample { public static
void main(String[] args) { B objb=new
B();//object of child class objb.hello();//call
the method in child class
}
}
Example #2
This program helps in demonstrating the super keyword while referring to the same method
in a parent class. Here, hello() is a method that is available in both classes.
32
//Java program to illustrate Super keyword to refer same method in parent class
//parent class class
A{
protected String name="ann";
public void hello() {
System.out.println("I am " + name);
}
}
//child classs class B
extends A {
public String name="Anna";//variable which is same in parent class
//sample method which is same in parent class public
void hello() {
System.out.println("I am " + name);
}
//method to call the hello() method in parent and child class public
void test()
{ hello();
super.hello();
}
}
//main class
public class SuperExample { public static
void main(String[] args) { B objb=new
B();//object of child class objb.test();//call
the method in child class
}}
Example #3
This program calls the constructor of the parent class using the super keyword. //Java
program to illustrate Super keyword to refer constructor in parent class
//parent class class
A{
//constructor of parent class
A() {
System.out.println("I am Kavya Madhavan"); }
}
//child class class B
extends A { //constructor
of child class
B() { super();
System.out.println("I am Dileep Menon");
}
}
//main class
public class SuperExample { public
static void main(String[] args) {
B objb=new B();//object of child class
}
}
33
Example #4
This program demonstrates the usage of a super keyword to refer to the parameterized
constructor of a parent class.
//Java program to illustrate Super keyword to refer parameterised constructor in parent class
//parent class
class A {
//constructor of parent class
A() {
System.out.println("I am Kavya Madhavan"); }
//parameterised constructor
A(String name) {
System.out.println("I am " + name);
}
}
//child class class B
extends A { //constructor
of child class
B() {
super("Renuka");
System.out.println("I am Dileep Menon");
}
}
//main class
public class SuperExample { public
static void main(String[] args) {
B objb=new B();//object of child class
}
}
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java. The condition for method overriding is a child class should have
the same name, same parameters list or other in words method signature and same return type
as a method in its parent class, then the method in the child class is said to override the method
of its parent class.
34
class Employee{
float salary = 40000;
void incrementSalary(double hike) {
System.out.println("The Employee incremented salary is :" +(salary + (salary * hike)) );
}
}
class PermanentEmp extends Employee{
void incrementSalary(double hike) {
System.out.println("The Permanent Employee incremented salary is :" +(salary + (salary *
hike)) );
}
}
class TemporaryEmp extends Employee{
void incrementSalary(double hike) {
System.out.println("The Temporary Employee incremented salary is :" +(salary + (salary *
hike)) );
}
}
public class p1
{
public static void main(String args[]){
Employee e =new Employee( );
PermanentEmp p = new PermanentEmp();
TemporaryEmp t = new TemporaryEmp();
// based on an object it decide which class incrementSalary() method to be execute
e.incrementSalary(0.2);
p.incrementSalary(0.5);
t.incrementSalary(0.35);
}
}
Dynamic Method Dispatch
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
when we call an overridden method of child class through its parent type reference (this
phenomenon in java is referred to as “Upcasting”), then the type of the object indicates which
method or functionality will be invoked. Making of this decision happens during runtime by
JVM after the compilation of code. Hence it is called as Run time polymorphism.
It is also referred as “Dynamic method dispatch”. Reason being named so, due to the fact that
functionality of method is dynamically decided in run time as per the object by JVM
It is also called “Late binding”, because binding of method and object, which means the
functionality of which object’s method will be displayed, is decided late i.e. after compilation.
class Shape
{ void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape
35
{ void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape
{ void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape
{ void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism
{ public static void main(String args[])
{
Shape s=new Shape();
Rectangle r=new Rectangle();
Circle c=new Circle();
Triangle t=new Triangle();
s.draw(); s=r;
s.draw();
s=c;
c.draw(); s=t;
t.draw();
}
}
class A {
final void meth()
{
System.out.println("This is a final method.");
}}
class B extends A
{ void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}}
ii. Using final to Prevent Inheritance
final class A {
36
// ...
}
// The following class is illegal.
class B extends A {
// ERROR! It is illegal for B to inherit A since A is declared as final
// ...
}
1.26. Abstract Classes and Methods
Abstract Class
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Syntax:
abstract Class_Name
Abstract Methods
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Note:
Example 1
abstract class Bike
{ abstract void run();
}
class Honda4 extends Bike
{ void run()
{
System.out.println("running safely");
}
37
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Example 2
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user class
Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user class
TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1(); //In a real scenario, object is provided through method, e.g.,
getShape() method s.draw();
}
}
Example 3
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike
{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
38
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike
{ void run()
{
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2
{ public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
39