0% found this document useful (0 votes)
24 views

Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

JAVA PROGRAMMING

UNIT I
UNIT I INTRODUCTION TO OOPS
CONCEPTS AND CLASSES
Introduction to Object Oriented Programming, Java buzzwords, Java
Programming Basics, Sample programs, Data types and operators,
Control statements. Classes: Classes, Objects, Methods, Constructors,
this and static keywords, Method and Constructor Overloading, Access
modifiers, Polymorphism. Arrays: One Dimensional and multi-
dimensional arrays
Before object Oriented Programming???
Procedural Programming Language : -
• Divided a program into a set of functions.
• Data stored in a bunch of variables. Functions
that operate on the data. This style of
programming is very simple and
straightforward.
• If make a change to one function, several others
function break. It becomes problematic.
Object Oriented Programming came to solve this
problem.
Object Oriented Programming
Object Oriented Programming,
• Combine a group of related variables and functions
into a unit, call that unit a object.
• Refer these variables as properties; Refer these
functions as methods.
Let us example,
Java User Input (Scanner)
• The Scanner class is used to get user input, and it is found in the java.util package.
Read Integer:-
int num1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Sum of these numbers: "+ num1);
Read String:-
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
Introduction to object Oriented Programming
• Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects.
• Object Oriented programming is a programming style which is
associated with the concepts like class, object, Inheritance,
Encapsulation, Abstraction, Polymorphism.
• Most popular programming languages like Java, C++, C#, Ruby,
etc. follow an object-oriented programming paradigm.
• It simplifies software development and maintenance by providing
some concepts:
Contd…Introduction to object Oriented
Programming
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
• Objects have states and behaviors.

• Example: A dog has states - color, name, breed as well as


• behavior such as wagging their tail, barking, eating.

• An object is an instance of a class.

• An object contains an address and takes up some space in memory.

• Objects can communicate without knowing the details of each


other's data or code
Class
• Collection of objects is called class. It
is a logical entity.
• Structure of an object it defines the
working of an object. class My {
private String name;
• A class can also be defined as a name=“oops”
blueprint from which you can create private int decimal = 100;
an individual object. }
public class demo{
• Class doesn't consume any space. public static void main(){
My obj = new My();
Example, }
}
Encapsulation
• Encapsulation is the mechanism that binds together code and the
data it (code) manipulates, and keeps both safe from outside
interference and misuse.
• The data is not accessible to the outside world and only those
functions which are wrapping in the class can access it.
• This insulation of the data from direct access by the program is called
data hiding or information hiding.
Abstraction
• Data abstraction refers to, providing only needed information to the
outside world and hiding implementation details.
• Use keyword : abstract
• It cannot be instantiated of abstract class.
• Abstract method is used only in abstract class.
• For example, while driving a car, you do not have to be concerned
with its internal working. Here you just need to concern about parts
like steering wheel, Gears, accelerator, etc.
• In java, we use abstract class and interface to achieve abstraction.
Polymorphism
• Polymorphism in Java is a concept by which we can perform a single
action in different ways.
• Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
• There are two types of polymorphism in Java: Static Polymorphism
(compile-time polymorphism) and Dynamic Polymorphism (runtime
polymorphism).
• We can perform polymorphism in java by method overloading and
method overriding.
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object.

• It is an important part of OOPs (Object Oriented programming


system).

• Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

• Java Inheritance (Subclass and Superclass)


• superclass (parent) - the class being inherited from
• subclass (child) - the class that inherits from another class
Data Types
• Data types specify the different sizes and values that can be stored in
the variable.
• There are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
• Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
Data Types Contd..
Example – Data Types

public class MyClass { System.out.println(myNum);


public static void main(String[] args) { System.out.println(myFloatNum);
int myNum = 5; System.out.println(myLetter);
float myFloatNum = 5.99f; System.out.println(myBool);
char myLetter = 'D’; System.out.println(myText);
boolean myBool = true; }
}
String myText = "Hello";
Data Types Contd..
Primitive Data Types
Why are they called primitive data types?
• Primitives supported by each programming language are sometimes
called "built-in data types" since they store values directly in memory.
• A primitive data type specifies the size and type of variable values, and it has
no additional methods.
• There are eight primitive data types in Java:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
Data Types Contd..
Byte
• The byte data type can store whole numbers from -128 to 127.
• This can be used instead of int or other integer types to save memory
when you are certain that the value will be within -128 and 127
• Example,
byte myNum = 100;
System.out.println(myNum);
Short
• The short data type can store whole numbers from -32768 to
32767
• Example,
short myNum = 5000;
System.out.println(myNum);
Data Types Contd..
Int
• The int data type can store whole numbers from -2147483648 to
2147483647.
• Example,
int myNum = 100000;
System.out.println(myNum);
Long
• The long data type can store whole numbers from -9223372036854775808
to 9223372036854775807.
• This is used when int is not large enough to store the value. Note that you
should end the value with an "L“
• Example,
long myNum = 15000000000L;
System.out.println(myNum);
Data Types Contd..
Non Primitive Data Types
• Non-primitive data types are called reference types because they refer to
objects.
• Non-primitive data types store references to values rather than the
values themselves. Examples of non-primitive Java data types
include arrays and classes
There are five types of non-primitive data types in Java. They are as follows:
1.Class
2.Object
3.String
4.Array
5.Interface
Data Types Contd..
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive
types are created by the programmer and is not defined by Java (except for
String).
• Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive
types have all the same size.
• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
Operators in Java
• Java provides a rich set of operators to manipulate variables. We can
divide all the Java operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic Operators
• Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical
operations.
Operators in Java..Contd..
Arithmetic Operators example:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Relational Operators
• These operators are used to check for relations like equality, greater than, less
than.
• They return boolean result after the comparison and are extensively used in
looping statements as well as conditional if else statements.
Operators in Java..Contd..
Relational Operators example:
Relational comparison < > <= >=
equality == !=

public class MyClass {


public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x < y); // returns false because 5 is not less than 3
}

Logical Operators
Logical operators are used to determine the logic between variables or
values
Operators in Java..Contd..
Logical Operators example:
Operator Name Description Example
&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is x < 5 || x < 4
true
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true

public class MyClass {


public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because ! (not) is used to reverse the
result
}
}
Operators in Java..Contd..
Assignment Operators
• Assignment operators are used to assign values to variables.
Operator Example
= C = A + B will assign value of A + B into C
+= C += A is equivalent to C = C + A
>>= C >>= 2 is same as C = C >> 2
%= C %= A is equivalent to C = C % A

Assignment Operators example:


public class MyClass {
public static void main(String[] args) {
int x = 10;
System.out.println(x); //10
}
}
Operators in Java
Bitwise Operators
• These operators are used to perform manipulation of individual bits of a number.
• Java defines several bitwise operators, which can be applied to the integer types, long,
int, short, char, and byte.
• Bitwise operator works on bits and performs bit-by-bit operation.
• Assume if a = 60 and b = 13; now in binary format they will be as follows −
• a = 0011 1100
• b = 0000 1101
---------------------
• a&b = 0000 1100 (AND operator – Returns true(1) if both arguments are true.
• a|b = 0011 1101 (OR operator – Returns true(1) atleast one argument is true.
• a^b = 0011 0001 (XOR operator – Returns true(1) if both argument are different
• ~a = 1100 0011 (One’s Compliment- Unary Operator which returns the one’s
compliment representation of the input value, i.e., with all bits inversed)
Operators in Java
~a = 1101 0110 , (Two’s Compliment – add one(1) with input value)
1101 0110 (Input value)
0010 1001 (Converted to 1’s Compliment)
+1 (Add 1 to find 2’s compliment)
----------------
0010 1010
----------------
<< (left shift) Takes two numbers, left shifts the bits of the first operand,
the second operand decides the number of places to shift.
0011
0110
1100
Operators in Java
>> (right shift) Takes two numbers, right shifts the bits of the first
operand, the second operand decides the number of places to shift.
1010 #include<stdio.h>
int main()
0101 {
unsigned char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
0010 printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}
Operators in Java
Miscellaneous Operators
• Java Ternary or Conditional Operator
• Java Member Access Operator
• Java Comma Operator
• Java Array Index Operator
• Java new Operator
Java Ternary or Conditional Operator
• Java provides a special operator that is called ternary or conditional
operator.
• This operator is a set of two symbols that are ? and :
Operators in Java..Contd..
• Both symbols collectively form the conditional operator.
/* TernaryOperatorDemo.java */
public class TernaryOperatorDemo
{
public static void main(String[] args)
{
int n = 10;
boolean flag = (n % 2 == 0 ? true : false );
System.out.println(n + " is even? " + flag);
}
}

OUTPUT
======
10 is even? true
Operators in Java..Contd..
Java Member Access Operator
• The Java member access operator is a dot (.) symbol that is used to
access data members and member methods of a class by its objects.
Java Comma Operator
• Java comma operator is a ',' sign that is used to separate function
arguments, and to declare more than one variable of same type in
one statement.
Java Array Index Operator
• Java array index operator, a set of square brackets ([]), is used to
declare and access array elements.
Operators in Java
Java new Operator
• The Java new operator is used to create a new object.
• Operator new is a Java keyword.
• It is followed by a call to a constructor, which initializes the new
object.
• Note that declaring an object and creating an object are two different
things.
• Simply declaring a reference variable does not create an object.
• For that, we need to use the new operator. The new operator creates
an object by allocating memory to it and returns a reference to that
memory location.
Operators in Java..contd..
public class constructordemo {

int value1;
int value2;
constructordemo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
constructordemo d1 = new constructordemo();
d1.display();
}
}
Control statements
• Java control statements cause the flow of execution to advance and
branch based on the changes to the state of the program.
• Control statements are divided into three groups:
1) selection statements allow the program to choose different parts of
the execution based on the outcome of an expression
2) iteration statements enable program execution to repeat one or
more statements
3) jump statements enable your program to execute in a non-linear
fashion
A program can execute from top to bottom but if we use a control
statement.
Control statements..Contd..
Simple if Statement
• Simple if statement is the basic of decision-making statements in Java.
It decides if certain amount of code should be executed based on the
condition.
class ifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Control statements..Contd..
if…else Statement
• In if…else statement, if condition is true then statements in if block
will be executed but if it comes out as false then else block will be
executed.
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Control statements..Contd..
Nested if statement
• Nested if statement is if inside an if block. It is same as normal if…else
statement but they are written inside another if…else statement.
class nestedifTest else
{ System.out.println("i is greater than 10 and
public static void main(String args[]) odd number");
{ }
int x = 25; else
{
if (x > 10) System.out.println("i is less than 10");
{ }
if (x%2==0) System.out.println("After nested if
System.out.println("i is greater than 10 and statement");
even number"); }
Control statements..Contd..
Switch Statement
• Java switch statement compares the value and executes one of the
case blocks based on the condition. It is same as if…else if ladder.
Rule:
• case value must be of the same type as expression used in switch
statement
• case value must be a constant or literal. It doesn’t allow variables
• case values should be unique. If it is duplicate, then program will give
compile time error
Control statements..Contd..
class switchDemo{ case 2:
public static void main(String args[]){ System.out.println("i is 2");
int i=2; break;
switch(i)
{ default:
case 0: System.out.println("i is not in the
System.out.println("i is 0"); list");
break; break;
case 1: }
System.out.println("i is 1"); }
break; }
Control statements..Contd..
Looping Statements in Java
• Looping statements are the statements which executes a block of code repeatedly
until some condition meet to the criteria.
• Loops can be considered as repeating if statements.
• There are 3 types of loops available in Java.
• for
• while
• do-while
For Statement
• It is the most common and widely used loop in Java.
• It is the easiest way to construct a loop structure in code as initialization of a
variable, a condition and increment/decrement are declared only in a single line of
code.
• It is easy to debug structure in Java.
Control statements..Contd..
• It is the easiest way to construct a loop structure in code as
initialization of a variable, a condition and increment/decrement are
declared only in a single line of code.
• It is easy to debug structure in Java.
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
//1 2 3 4 5
Control statements..Contd..
while
• while loops are simplest kind of loop. It checks and evaluates the
condition and if it is true then executes the body of loop.
• This is repeated until the condition becomes false.
class whileLoopTest Output:
{ 1
public static void main(String 3
args[]) 5
7
{ 9
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Control statements..Contd..
do…while
• do…while works same as while loop.
• It has only one difference that in do…while, condition is checked after
the execution of the loop body.
• That is why this loop is considered as exit control loop.
• In do…while loop, body of loop will be executed at least once before
checking the condition. class dowhileLoopTest do
{ {
public static void System.out.println(j);
main(String args[]) j = j+1;
{ } while (j <= 10);
int j = 10; }
} //10
Constructor and Constructor Overloading
• 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.
• Every time an object is created using the new()
keyword, at least one constructor is called.
• Unlike Java methods, a constructor has the same
name as that of the class and does not have any
return type.
• There are two types of constructors in Java: no-
argconstructor, parameterized constructor
and default constructor.
Constructor Example
Constructor Types - No-Arg Constructors
• a Java constructor may or may
not have any parameters
(arguments).
• If a constructor does not accept
any parameters, it is known as
a no-argument constructor. For
example,
private Main() {
// body of the constructor
}
Output:
Constructor Types - Parameterized Constructor
• A Java constructor can also
accept one or more parameters.
Such constructors are known as
parameterized constructors
private Main(String lang) {
// body of the constructor
}
Output:
Constructor Types - Default Constructor
• If we do not create any
constructor, the Java compiler
automatically create a no-arg
constructor during the
execution of the program.
• This constructor is called
default constructor.

Output:
Rules on Java Constructor
• Constructors are invoked implicitly when you instantiate objects.

• The two rules for creating a constructor are:


The name of the constructor should be the same as the class.
A Java constructor must not have a return type.

• If a class doesn't have a constructor, the Java compiler automatically creates


a default constructor during run-time.

• A constructor cannot be abstract or static or final.

• A constructor can be overloaded but can not be overridden.


Constructor Overloading
• Similar to
Java method ov
erloading
, we can also
create two or
more
constructors
with different
parameters.
This is called
constructors
overloading.
Access Modifiers in Java
• The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
• There are four types of Java access modifiers:
1.Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2.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.
3.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.
4.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.
What is use of this keyword?
Use of ‘this’ keyword
The this keyword refers to the current object in a method or
constructor. The most common use of the this keyword is to
eliminate the confusion between class attributes and parameters
with the same name.
Usage of Java this keyword,
1.this can be used to refer current class instance variable.
2.this can be used to invoke current class method (implicitly)
3.this() can be used to invoke current class constructor.
4.this can be passed as an argument in the method call.
5.this can be passed as argument in the constructor call.
6.this can be used to return the current class instance from the method.
What is use of this keyword?
Example #1 – this: to refer current class instance variable

there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
What is use of this keyword?
Example #2 – this: to invoke current class method

Output
hello n
hello m
What is use of this keyword?
• Example #3 – to invoke current class constructor

Output
hello a
10
What is use of this keyword?
• Example #4 – Calling parameterized constructor from default
constructor:

Output
5
hello a
What is use of static keyword?
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and
nested classes. The static keyword belongs to the class than an
instance of the class.
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable gets memory only once in the class area at the time
of class loading.
• It makes your program memory efficient (i.e., it saves memory).
What is use of static keyword?
• Example #1:
“Static Variable”

Output???
What is use of static keyword?
• Example #2 – Static Method:
• If you apply static keyword
with any method, it is known as
static method.
• A static method can be invoked
without the need for creating an
instance of a class.

Output:
from m1
What is use of static keyword?
• Example #3 – Static class
• A static class is a class that is
created inside a class, is called a
static nested class in Java.
• It cannot access non-static data
members and methods. It can be
accessed by outer class name.
• The static nested class cannot
access non-static (instance) data
members

Output:
data is 30
Arrays
• Normally, an array is a collection of similar type of elements which
have a contiguous memory location.
• Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar
elements.
• We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
Arrays..Contd..
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array.
• It doesn't grow its size at runtime.
• To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Arrays..Contd..
Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

//declaration and instantiation


int a[]=new int[5];
Arrays..Contd..example#1
class Testarray{ Output:
public static void main(String args[]){ 10
20
int a[]=new int[5];//declaration and 70
instantiation 40
a[0]=10;//initialization 50
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//printing array
for(int i=0;i<a.length;i++)//length is the
property of array
System.out.println(a[i]);

}}
Arrays..Contd..example#2
import java.util.Scanner; for (int i = 0; i < count; i++)
public class JavaExample {
{ num[i] = scan.nextInt();
public static void main(String[] args) }
{
int count; scan.close();
System.out.print("Array Elements are: ");
//User inputs the array size for (int i = 0; i < count ; i++)
Scanner scan = new Scanner(System.in); {
System.out.print("Enter number of System.out.print(num[i] + ", ");
elements you want in the array: "); }
count = scan.nextInt(); }
}
int num[] = new int[count];
System.out.println("Enter array
elements:");
Two Dimensional Array
• The two-dimensional array can be defined as an array of arrays.
• The 2D array is organized as matrices which can be represented as the
collection of rows and columns.
Declaration of two dimensional Array in Java
• Consider the following example.
Two dimensional array:
int[][] twoD_arr = new int[10][20];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];
Two Dimensional Array
Example #1
class A {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

System.out.println("arr[0][0] = " +
arr[0][0]);
}
}
OUTPUT:???
Two Dimensional Array
What is use of this keyword?
Use of ‘this’ keyword
The this keyword refers to the current object in a method or
constructor. The most common use of the this keyword is to
eliminate the confusion between class attributes and parameters
with the same name.
Usage of Java this keyword,
1.this can be used to refer current class instance variable.
2.this can be used to invoke current class method (implicitly)
3.this() can be used to invoke current class constructor.
4.this can be passed as an argument in the method call.
5.this can be passed as argument in the constructor call.
6.this can be used to return the current class instance from the method.
What is use of this keyword?
Example #1 – this: to refer current class instance variable

there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
What is use of this keyword?
Example #2 – this: to invoke current class method

Output
hello n
hello m
What is use of this keyword?
• Example #3 – to invoke current class constructor

Output
hello a
10
What is use of this keyword?
• Example #4 – Calling parameterized constructor from default
constructor:

Output
5
hello a
What is use of static keyword?
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and
nested classes. The static keyword belongs to the class than an
instance of the class.
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable gets memory only once in the class area at the time
of class loading.
• It makes your program memory efficient (i.e., it saves memory).
What is use of static keyword?
• Example #1:
“Static Variable”

Output???
What is use of static keyword?
• Example #2 – Static Method:
• If you apply static keyword
with any method, it is known as
static method.
• A static method can be invoked
without the need for creating an
instance of a class.

Output:
from m1
What is use of static keyword?
• Example #3 – Static class
• A static class is a class that is
created inside a class, is called a
static nested class in Java.
• It cannot access non-static data
members and methods. It can be
accessed by outer class name.
• The static nested class cannot
access non-static (instance) data
members

Output:
data is 30
Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single
action in different ways. Polymorphism is derived from 2 Greek words:
poly and morphs. The word "poly" means many and "morphs" means
forms. So polymorphism means many forms.
• There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
Type 1: Compile-time polymorphism
• It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
• Method Overloading: When there are multiple functions with the same
name but different parameters then these functions are said to
be overloaded.
Polymorphism in Java
Example #1 Method Overloading
Polymorphism in Java
Example #2 Method Overloading
Polymorphism in Java
Example #3 Method Overloading
Polymorphism in Java
Type 2: Run Time polymorphism
• It is also known as dynamic polymorphism. This type of polymorphism is achieved
by method overriding.
• Dynamic polymorphism is a process or mechanism in which a call to an overridden
method is to resolve at runtime rather than compile-time. It is also known as
runtime polymorphism.

Rules for Java Method Overriding

1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship (inheritance).
Polymorphism in Java
Example #1 Method Overriding
Polymorphism in Java
Example #2 Method Overriding

OUTPUT
subclass1
subclass2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy