100% found this document useful (1 vote)
223 views

CTOOD CO1 CO2 Notes

This document provides an overview of key Java concepts including object-oriented programming features, the Java compilation process, primitive data types and arrays, static methods, access specifiers, control statements, wrapper classes and casting, constructors, inheritance, polymorphism, the singleton pattern, and the Java API. It also discusses Java virtual machines, bytecode, and the Java development toolkit.

Uploaded by

kalyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
223 views

CTOOD CO1 CO2 Notes

This document provides an overview of key Java concepts including object-oriented programming features, the Java compilation process, primitive data types and arrays, static methods, access specifiers, control statements, wrapper classes and casting, constructors, inheritance, polymorphism, the singleton pattern, and the Java API. It also discusses Java virtual machines, bytecode, and the Java development toolkit.

Uploaded by

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

S10 & S3 CTOOD

Introducing Object oriented programming


Advantages of Object-Oriented programming and its key
features, Java program hierarchy and compilation process.
Primitive Data Types and Arrays
Building Static Methods.
CO-1
Modularization and access specifiers
Modularization Class and Package Level
Logic building using control statements and iterative
statements.
Wrapper classes and implicit casting. Command Line Arguments.
Method Overloading.

Classes and Objects, and Inner classes.


Accessors, mutators, and toString().
Constructors – default, user -defined and parametrized.
Introduction to Java API, Scanner class, console -based IO.
Constructor chaining, this keyword, array of objects,
CO-2
Aggregation and composition
ArrayList, SOLID design principles.

Inheritance, method overriding, dynamic polymorphism, dynamic


method dispatch,
Singleton classes.
create
Programming software

develop instructions tell device


what to do

Role of OS

Microsoft
MAC Linux
Windows

WebBrowser runs

Application When Installed

ByteCodes

JVM

Source Complier ByteCode JVM

JVM

JVM Java Virtual Machine


Unlike Many Java is not Specific
Programming Languages compiled Manner

Target System should


have JVM(JRE) installed
in it

JDK
Java Development ToolKit

Complier JRE
Java RunTime Environment

Java ClassFile
input
JVM
Program BYTECODE

Output
Complier +

Java
compliation
class
bytecode
JVM

Output
History

* Java was developed by Team Lead by James


software program SunMicroSystems

instructions tell device


* Oak Java WebApplications
what to do

* Write a program Once & run it anywhere

Object
Simple Oriented

When Installed Secure


Java
Features
Robust

Interpreter for portable


MAC

Interpreter for Java BuzzWo


Windows
Platform Independent
Interpreter for Runs on any Enivironment
Linux
Object Oriented Concepts

Simple
No concept of Pointers&E
Allocation,Structures,Operato
into a platform Secure
Independent Implement Internet Applications
BYTECODE
Robust
checking early errors
BYTE CODE
WEB Intrepreted by
JVM portable
Runs and implements in another environ

multithreading
concurrent execution of differ
improves CPU utilization
Distributed Environment Application
software that can run on multip
Architectural Neutral
Irrespective of Architecture memory a
unTime Environment size of DataType depends on O

JDK

predefined words given by complier wh

Complier + JRE
import implements classes and methods
JVM
imports package

class collection of objects


blueprint or template in which object s

this refers to current object


super access methods from oneclass to anoth

extends used in inheritance which acquires the

package no.of classes accessing

return returns value or variable

try and cexception handling

private
access
public
specifier
protected
Team Lead by James Gosling at
croSystems

ations

run it anywhere

* object is an entity
* program has many objec

class
is a blueprint or tem
Distributed can have n no.of obj
defines data membe

Architectural object
Neutral is a real world enti
instance of class
multithreading
Abstraction

Java BuzzWords

ny Enivironment Encapsulation

Abstraction,Classes &
Objects,Encapsulation,Inheritance,polymorphism
Name
oncept of Pointers&Explicit memory Variables
n,Structures,Operator Overloading etc.. Methods

net Applications

garbage collector

exception handling
Inheritance
acquires features o
nts in another environment achieves inheritanc
reusability of code

t execution of different parts of same program at a time. polymorphism


CPU utilization performing same ta
Application invoking method in d
that can run on multiple systems connected in internet poly means one and
2 ways
rchitecture memory allocation to variables will not wary runtime polymorphi
ataType depends on OS

Java Keywords(lowercase) * holds value


given by complier which has some specific task * assigned with datatype
* name of memory location
3 types of Variables
s and methods local
inside of body of m
can be accessed onl
other methods in th
late in which object should follow instance

variable declared
outside the m
variable declared
outside the m

rom oneclass to another class(inheritance)


static
e which acquires the properties of one class to another class cannot be local
created as a single

Example 1:
access
specifier

public class Simple


{
access
specifier

public static void m


{
System.out.
}
}

Example 2:

public class Addition


{
public static void
{

}
}

Example 3:

public class VarExample


{
static int data=50;
public void display()
{

}
}
OOPs (Object Oriented Programming System)

OOP

Way of Solving

Complex Program

sub sub sub


programs programs programs

t is an entity
gram has many objects which are used to solve real world entity

is a blueprint or template in which the object has to follow


can have n no.of objects
defines data members & methods of an object.

is a real world entity having some properties or ttask to be performed


instance of class

abstract
Hiding Data and shows only essential parts.
Hides the implementation details
Ex: Android PlayStore
.app .exe

Bindind data & functions into single entity


Ex: Class

Name Student
Variables name
Methods roll no
doj
read()
write()
play()

acquires features of one class to another class


achieves inheritance by using extends keyword
reusability of code

performing same task in different ways


invoking method in different ways
poly means one and morphism means many

runtime polymorphism compile time polymorphism

Variables

ned with datatype


of memory location
of Variables

inside of body of method


can be accessed only within that method
other methods in that class can't access

variable declared inside a class but can be accessed


outside the method by using object creation
variable declared inside a class but can be accessed
outside the method by using object creation

cannot be local
created as a single copy and shared among all instance of class

Basic Program

class
without
name
any
object
class Simple
method
name
no return
vale arguments

public static void main(String args[])

System.out.println("Hello Java");

method

class Addition

public static void main(String args[])

int x=10;
int y=25;
int z=x+y;
System.out.println("Sum of X+Y=",z);
class VarExample

static int data=50; it is a static variable


public void display()

int n=90; it is a local variable


System.in

Reads Data
from Keyword

Values
HardCore
Scanner
CommandLineArguments
Files
IO Streams(Bytes of Data)

System.out System.err

Displays Data Displays error


on Screen Message

Assign
Read
Runtime
Files
1 2
Addition using hardcore values. Addition using scanner function.

public class Sample{ import java.util.Scanner;


public static void main(String args[]) public class Sample{
{ public static void main(String args[])
int a=4; {
int b=5; Scanner input=new Scanner(System.in);
int c=(a+b); int a=input.nextInt();
System.out.println(c); int b=input.nextInt();
} int c=(a+b);
} System.out.println(c);
}
}

Sum of array elements using Sum of array elements using console


HardcoreValues. Values

public class ArrayExample import java.util.Scanner;


{ public class Sample{
public static void main(String args[]) public static void main(String args[])
{ {
int sum=0; int n,i,sum=0;
int[] a = new int[5]; Scanner input=new Scanner(System.in);
a[0]=1; n=input.nextInt();
a[1]=2; int a[]=new int[n];
a[2]=3; for(i=0;i<n;i++)
a[3]=4; a[i]=input.nextInt();
a[4]=5; for(i=0;i<n;i++)
{
for(int i=0;i<a.length;i++) sum=sum+a[i];
{ }
sum=sum+a[i]; System.out.println(sum);
} }
System.out.println(sum); }
}
}
foreach
Sum of array elements using
HardcoreValues. public class ArrayExample
{
public class ArrayExample public static void main(String args[])
{ {
public static void main(String args[])
{ int a[]={1,2,3,4,5};
int s=0;
int a[]={1,2,3,4,5}; for(int i:a)
int s=0; {
for(int i=0;i<a.length;i++) s+=i;
{
s+=a[i]; }
System.out.println(s);
} }
System.out.println(s); }
}
}
3
ner function. Addition using command line arguments

public class Sample{


public static void main(String args[])
ring args[]) {
int a=Integer.parseInt(args[0]);
anner(System.in); int b=Integer.parseInt(args[1]);
int c=(a+b);
System.out.println(c);
}
}

s using console Sum of array elements using


command line arguments.

public class Sample{


public static void main(String args[])
ring args[]) {
int n,i,sum=0;
n=args.length;
anner(System.in); int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=Integer.parseInt(args[i]);
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
System.out.println(sum);
}
}
h

(String args[])
Modularization

* Dividing a Program into subprograms is called modularization


* Modularization is done in 3 ways
a.) method b.)Class c.)Package
* It means we can divide our program into set of methods or classes or packag

Method Modularization
* Dividing program into set of methods

public class ModExample


{
public static void main(String args[])
{
int n,res;
n=5;
res=factorial(n);
System.out.println("Factorial="+res);

n=2;
res=factorial(n);
System.out.println("Factorial="+res);

n=3;
res=factorial(n);
System.out.println("Factorial="+res);

}
public static int factorial(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
}
or classes or packages

Class Modularization
* Dividing program into classes

class Demo
{
public static int factorial(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f* i ;
return f;
}
}

public class Fact


{
public static void main(String args[])
{
int n=5;
System.out.println("Factorial"+Demo.factorial(n));
}
}
Package Modularization
* Dividing program into different package
package mypack1;
public class Demo
{
public static int factorial(int n)
{
int f,i ;
for(i=1;i<=n;i++)
f=f*i ;
return f;
}
}

package mypack2;
import mypack1.Demo;
public class MyFact
{
public static void main(String args[])
{
int n=5,res;
res=Demo.factorial(n);
}
}
getterandsetters
1 Getters and Setters are Two Conventional methods that are used for retrieving and updating v
2 Getters and Setters are also known as Accessors and Mutators

Usage of this keyword Usage of getters and setters

package gettersetter; package gettersetter;


class AmDemo
{
private int x;
public class DemoOfThis { public void setX(int x)
public static void main(String args[]) {
{
Account obj=new Account(); }
obj.setData(20,30); public int getX()
obj.showData(); {
}
} }
class Account public void display()
{ {
int a,b;
public void setData(int a,int b) }
{ }
// this.a=a; public class Am {
// this.b=b;
a=a;
b=b;
}
public void showData()
{
System.out.println(""+a); }
System.out.println(""+b);
}
}

when the above program is executed then the output is


value of a=0
value of b=0

In this program the parameter of setData() are declared as a and b


and also data also declared as a and b.
During Execution the complier is confused whether "a" on the leftside
of the assigned operator is the instance variable or local variable.
Hence it doesn't set the value of a when the method setData is invoked.
The solution for this problem is using this keyword.
this is a keyword in java which acts as a reference and used to refer to the
current object Data Number.
So we can overcome the above problem by Writing the Statement
this.a=a;
this.b=b;

Usage of getters and setters Example 2

package gettersetter;

public class MyTest {


public static void main(String args[])
{
//Sample S;
Sample S=new Sample();
S.setX(12.5);
S.setY(14.2);
S.setR(11.2);
double a=S.areaRec();
double p=S.perRec();

double ac=S.areaCircle();
double cc=S.circumCircle();

System.out.println("Area="+a);
System.out.println("Perimeter="+p);
System.out.println("AOC="+ac);
System.out.println("AOCC="+cc);

}
class Sample
{
public double x,y,r;

public void setX(double x)


{
this.x=x;
}
public double getX()
{
return x;
}

public void setY(double y)


{
this.y=y;
}
public double getY()
{
return y;
}

public void setR(double r)


{
this.r=r;
}
public double getR()
{
return r;
}

public double areaRec()


{
double area=x*y;
return area;
}

public double perRec()


{
double per=2*(x+y);
return per;
}

public double areaCircle()


{
double area=r*r*Math.PI;
return area;
}

public double circumCircle()


{
double circum=2*r*Math.PI;
return circum;
}
}
s
or retrieving and updating value of a variable.

f getters and setters Example 1

package gettersetter;
class AmDemo

private int x;
public void setX(int x)

this.x=x;

public int getX()

return this.x;

public void display()

System.out.println("X Value"+getX());

public class Am {
public static void main(String args[])
{
AmDemo t=new AmDemo();
t.setX(22);
t.display();
}
Getters and Setters without Validation
Example 1
class Arrperi{
private int l,b,r;
private double ar,pr,ac,pc;
public void setL(int l){
this.l=l;
}
public int getL(){
return this.l;
}
public void setB(int b){
this.b=b;
}
public int getB(){
return this.b;
}
public void setR(int r){
this.r=r;
}
public int getR(){
return this.r;
}
public double areaR(){
ar=getL()*getB();
return ar;
}
public double periR(){
pr=2*(getL()+getB());
return pr;
}
public double areaC(){
ac=getR()*getR()*Math.PI;
return ac;
}
public double periC(){
pc=2*getR()*Math.PI;
return pc;
}
public String toString(){
return "Area of Rectangle="+areaR()+" "+"Area of Circle="+areaC()+"
}

}
public class Rectangle{
public static void main(String args[]){
Arrperi a=new Arrperi();
a.setL(5);
a.setB(6);
a.setR(7);
System.out.println(a);
}
}
ithout Validation
Example 2
class Acc{
private long id,balance;
public void setId(long i) {
this.id=i;
}
public void setBal(long bal) {
this.balance=bal;
}
public long depoBal(long amo) {
balance=balance+amo;
return balance+amo;
}
public long
public void withdraw(long amo) {
balance=balance-amo;
}
public void deposit(long amo) {
balance=balance+amo;
}
public String toString() {
return "Id="+id+" "+"Balance="+balance;
}
}
public class Demo {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
Acc ac=new Acc();
System.out.println("Enter id,balance");
ac.setId(in.nextLong());
ac.setBal(in.nextLong());
boolean r=true;
while(r) {
int c;
System.out.println("Enter choice");
c=in.nextInt();
if(c==1) {
System.out.println("Enter amount");
ac.withdraw(in.nextLong());
}
else if(c==2) {
System.out.println("Enter amount");
ac.deposit(in.nextLong());
}
else if(c==3)
System.out.println(ac.toString());
else
r=false;
}
}
}
Getters and Setters with validation:
Example 1
import java.util.Scanner;
class Student{
private String name;
private long id;
public void setName(String n) {
this.name=n;
}
public String getName() {
return name;
}
public boolean setId(long i) {
if(i>=1 && i<=50) {
this.id=i;
return true;
}
else
return false;
}
public long getId() {
return id;
}
}
public class Registration {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the name:");
Student s=new Student();
s.setName(in.nextLine());
System.out.println("Enter the id number:");
if(s.setId(in.nextInt()))
System.out.print(s.getName()+" "+s.getId());
else
System.out.println("Invalid");
}
}
and Setters with validation:
Example 2
import java.util.Scanner;
class Menudri{
private int l,b,r;
public boolean setL(int le) {
if(le>0)
{
l=le;
return true;
}
else
return false;
}
public boolean setB(int br) {
if(br>0) {
b=br;
return true;
}
else
return false;
}
public boolean setR(int ra) {
if(r!=0) {
r=ra;
return true;
}
else
return false;
}
public int aR() {
int arear=l*b;
return arear;
}
public int pR() {
int perir=2*(l+b);
return perir;
}
public double aC() {
double areac=r*r*Math.PI;
return areac;
}
}
public class Ap {
public static void main(String args[]) {
Mendri m=new Mendri();
Scanner in=new Scanner(System.in);
boolean a=true;
while(a) {
int ch;
ch=in.nextInt();
switch(ch) {
case 1: {
if(m.setL(in.nextInt())&& m.setB(in.nextInt()))
System.out.println(m.aR()+" "+m.pR());
else
System.out.println("False");
break;
}
case 2:{
if(m.setR(in.nextInt()))
System.out.println(m.aC());
else
System.out.println("False");
break;
}
case 3:{
a=false;
break;

}
}

}
}
}
This KeyWord Usage Example 1
class Account public class DemoOfThis
{
int a,b;
public void setData(int a,int b)
{
this.a=a;
this.b=b;
//a=a;
//b=b;
}
public void showData()
{
System.out.println(""+a);
System.out.println(""+b);
}

Example 2
class AmDemo
{ public class Am {
private int x; public static void main(S
public void setX(int x) {
{
this.x=x;
}
public int getX() }
{ }
return this.x;
}
public void display()
{
System.out.println("X Value"+getX());
}
}

Example 3

class Sample public class MyTest {


{
public double x,y,r;

public void setX(double x)


{
this.x=x;
}
public double getX()
{
return x;
}

public void setY(double y)


{
this.y=y;
}
public double getY()
{
return y;
}

public void setR(double r) }


{
this.r=r;
}
public double getR()
{
return r;
}

public double areaRec()


{
double area=x*y;
return area;
}

public double perRec()


{
double per=2*(x+y);
return per;
}

public double areaCircle()


{
double area=r*r*Math.PI;
return area;
}

public double circumCircle()


{
double circum=2*r*Math.PI;
return circum;
}
}
public class DemoOfThis {
public static void main(String args[])
{
Account obj=new Account();
obj.setData(20,30);
obj.showData();
}
}

public static void main(String args[])

AmDemo t=new AmDemo();


t.setX(22);
t.display();

public class MyTest {


public static void main(String args[])
{
//Sample S;
Sample S=new Sample();
S.setX(12.5);
S.setY(14.2);
S.setR(11.2);

double a=S.areaRec();
double p=S.perRec();

double ac=S.areaCircle();
double cc=S.circumCircle();

System.out.println("Area="+a);
System.out.println("Perimeter="+p);
System.out.println("AOC="+ac);
System.out.println("AOCC="+cc);

}
Super Class
java.lang.object

immediate parent class object

create instance of subclass


instance of parent class is created implicitly
reffered by super reference variable

Example 1 refers immediate parent class instance variable


class Collegesk
{
String msgsk="admitted";
}
class Branchsk extends Collegesk
{
String msgsk="Selected Branch";
void status()
{
System.out.println(msgsk); prints msg of Branchsk
System.out.println(super.msgsk); prints msg of Collegesk
}
}
public class Testsk
{
public static void main(String args[])
{
Branchsk objsk=new Branchsk();
objsk.status();
}
}
Selected Branch
admitted

Example 3 To Invoke parent class Constructor


class Collegesk2
{
Collegesk2()
{
System.out.println("got admitted");
}
}
class Branchsk2 extends Collegesk2
{
Branchsk2()
{
super();
System.out.println("Branch Selected");
}
}
public class Testsk2
{
public static void main(String args[])
{
Branchsk2 objsk2=new Branchsk2();
}
}
usage of java super keyword

refers invokes invokes


immediate immediate immediate
parent parent parent
class class class
instance method constructor

Example2 To Invoke Parent Class


class Collegesk1
{
void statussk1()
{
System.out.println("admitted");
}
}
class Branchsk1 extends Collegesk1
{
prints msg of Branchsk void statussk1()
prints msg of Collegesk {
System.out.println("Selected Branch");
}
void report()
{
System.out.println("got Reg.NO");
}
void attend()
{
super.statussk1();
report();
}
}

public class Testsk1


{
public static void main(String args[])
{
Branchsk1 objbk=new Branchsk1();
objbk.attend();
}
}

Example 4
class Collegesk3
{
Collegesk3()
{
System.out.println("got admitted");
}
}
class Branchsk3 extends Collegesk3
{
Branchsk3()
{
System.out.println("Selected Branch");
}
}
public class Testsk3
{
public static void main(String args[])
{
Branchsk3 objsk3=new Branchsk3();
}
}

Note:

super() is added in each class constructor automatically by


complier if there is no super() or this().
Usage of Constructor

package myconstructor;

public class Student {


public static void main(String args[])
{
Student7 s1=new Student7();
System.out.println(s1.sno);
System.out.println(s1.sname);

Student7 s2=new Student7();


System.out.println(s2.sno);
System.out.println(s2.sname);
}

}
class Student7
this is Default parameterized
{ constructor
int sno;
String sname;
Student7() Here Construtor is Created
{
sno=457;
sname="Raj";
}
}

Rules for Construtor


1 Constructor Name should be same as as Class Name
2 Constructor doesn't have Return Type.

Usage of Constructor OverLoading

package myconstructor;

public class Emp7 {


String name;
int no;
Emp7()
{ Normal Constructor/
Default
name="Raj"; parameterized
no=99; Constructor
}
Emp7(String en,int n)
{
parameterized
name=en;
Constructor
no=n;
}
public static void main(String args[])
{
Emp7 e1=new Emp7();
Calling Constructors and
here it is OverLoaded Emp7 e2=new Emp7("Rahul",77);
System.out.println(e1.name);
System.out.println(e1.no);
System.out.println(e2.name);
System.out.println(e2.no);
}
}
Usage of Parameterized Constructor

package myconstructor;

public class Stud {


int id;
String sname; this is
Stud(int i,String n) parameterized
{ constructor
id=i;
sname=n;
}
void display()
{
System.out.println(""+id);
System.out.println(""+sname);
}
public static void main(String args[])
{

Stud s1=new Stud(111,"KARAN");


Stud s2=new Stud(222,"ARJUN");
s1.display();
s2.display();
}
}

Usage of Constructor OverLoading

package myconstructor;

public class Circle


{
private double radius=1;
private static int numberOfObject=0;
public Circle()
{ Normal Constructor/
Default
numberOfObject++; parameterized
} Constructor
public Circle(double newRadius)
{
parameterized
radius=newRadius;
Constructor
numberOfObject++;
}
public double getRadius()
{
return radius;
}
public void setRadius(double newRadius)
{
radius=(newRadius>=0)?newRadius:0;
creating methods }
for setters and
getters public static int getNumberOfObject()
{
return numberOfObject;
}
public double getArea()
{
return radius=radius*Math.PI;
}
public static void main(String[] args) {
Circle ob1 = new Circle(); main
System.out.println(ob1.getArea()); method
Circle ob = new Circle(10);
System.out.println(ob.getArea());
}
}
class Pcircle
{
double radius=1;
Pcircle()
{
}
Pcircle(double newRadius)
{
radius=newRadius;
}

double getArea()
{
return radius*radius*Math.PI;
}
double getPeri()
getters and {
setters return 2*radius*Math.PI;
}
void setRadius(double newRadius)
{
radius=newRadius;
}
}
Constructor Chaining

package myconstructor;

public class TempDemo


{
public static void main(String args[])
{
Temp t=new Temp();
}

}
class Temp
{
Temp()
{ this(5);
System.out.println("Default Constructor");
}
Temp(int x)
{
this(5,17);
System.out.println(x);
}
Temp(int x,int y)
{
System.out.println(x*y);
}
}

1 A constructor in Java is a specific method used in object creation of a class.


2 The constructor is invoked every time an object of the class is created
3 It can be used to assign values to the properties of the object at creation time
4 There can be multiple constructors in a Java class with different parameter lists.

Constructor chaining is used to invoke different implementations of


constructors of the same class/parent class at the object creation time.
There are two ways of chaining constructors based on how to call the constructor.
using this() keyword
 to call constructors of the same class
using super() keyword
to call constructors of the parent class

Constructor chaining example #2 – Constructors are chained using


this() keyword

package myconstructor;

public class BaseClass {

public BaseClass() {
//calling a three argument constructor of the same class
this("Male", "English", "1989/11/10");
System.out.println("I'm executed third!!!");
}

public BaseClass(String firstName, String surname, int idNo) {


System.out.println("I'm executed first!");
System.out.println("First name : " + firstName);
System.out.println("Surname : " + surname);
System.out.println("ID Number : " + idNo);
}

public BaseClass(String gender, String nationality, String birthDate) {


System.out.println("I'm executed second!!");
System.out.println("Gender : " + gender);
System.out.println("Nationality : " + nationality);
System.out.println("Birth Date : " + birthDate);
}
public static void main(String args[])
{
BaseClass t=new BaseClass();
}

}
Constructor chaining example #1 – Constructors are chained using
this() keyword

package myconstructor;

public class DerivedClass {

String firstName;
String country;
int age;

public DerivedClass() {
// calling one argument constructor
this("Maggie");
}

public DerivedClass(String firstName) {


// calling two argument constructor
this(firstName, 15);
}

public DerivedClass(String firstName, int age) {


// calling three argument constructor
this(firstName, age, "Australia");
}

public DerivedClass(String firstName, int age, String country) {


this.firstName = firstName;
this.age = age;
this.country = country;
}

void displayValues() {
System.out.println("First Name : " + firstName);
System.out.println("Country : " + country);
System.out.println("Age : " + age);
}

public static void main(String args[]) {


DerivedClass object = new DerivedClass();
object.displayValues();
}
}

We have declared four constructors for the DerivedClass. One with no


arguments and the other three with different arguments. Inside each
constructor this()keyword is used to call the next constructor of the same
class

package myconstructor;

public class DerivedClass7 extends BaseClass {

public DerivedClass7() {
//calling no argument constructor of the super class
super();
}

public DerivedClass7(String firstName, String surname, int idNo) {


//calling three argument constructor of the super class
super(firstName, surname, idNo);
}
ring birthDate) {
public static void main(String args[]) {
DerivedClass7 object2 = new DerivedClass7("Paul", "Wilson", 12345
DerivedClass7 object1 = new DerivedClass7();
}
}
country) {
super class

ing surname, int idNo) {


the super class

s7("Paul", "Wilson", 123456);


Default and Parameterised Constructor:

Default: Parameterised:
class Sample{ class Sample{
Sample(){ Sample(int x,int y){
System.out.println("Hai"); System.out.println(x+" "+y);
} }
} }
public class Test{ public class Test2{
public static void main(String args[]){ public static void main(String arg
Sample s=new Sample(); Sample s=new Sample(5,6);
} }
} }

Constructor chaining: class Example{


Example(int x,int y){
class Temp{ this(x);
int age; System.out.println(x+y);
String name,country; }
Temp(){ Example(int x){
this("Maggie");; this();
} System.out.println("Hai");
Temp(String name){ }
this(name,15); Example(){
} System.out.println("Hello sectio
Temp(String name,int age){ }
this(name,15,"India");
} }
Temp(String name,int age,String country){ public class Cc{
this.name=name; public static void main(String aar
this.age=age; Example e=new Example(5,6);
this.country=country; }
} }
void display() {
System.out.println(name+" "+age+" "+country);
}
}
public class Cc {
static int a=5;
public static void main(String args[]) {
Temp s2=new Temp();
s2.display();
}
}
Constructor chaining with inheritance:

int x,int y){ class Demo{


out.println(x+" "+y); Demo(){
this(50,55);
System.out.println("Default Constructor in Demo Class");
ass Test2{ }
atic void main(String args[]){ Demo(int x,int y){
s=new Sample(5,6); System.out.println("Parameterised constructor in Demo cl
}
}
class Parent extends Demo{
Parent(){
this("a","b");
ple(int x,int y){ System.out.println("Default Constructor in Parent Class");
}
m.out.println(x+y); Parent(String s1, String s2){
super();
System.out.println("Parameterised Constructor in Parent C
}
m.out.println("Hai"); }
public class Cc {
public static void main(String args[]) {
m.out.println("Hello section 10"); Parent p=new Parent();
}
}

atic void main(String aargs[]){


ple e=new Example(5,6);
Super() key word:

ing with inheritance: class Person{


Person() {
System.out.println("7");
}

ut.println("Default Constructor in Demo Class"); }


class Student extends Person{
void message() {
ut.println("Parameterised constructor in Demo class"); System.out.println("8");
}
Student() {
super();
message();
}
ut.println("Default Constructor in Parent Class"); }
public class ExampleCc {
s1, String s2){ public static void main(String args[]) {
Student s=new Student();
ut.println("Parameterised Constructor in Parent Class"); }
}

main(String args[]) {
Super. keyword with methods Constructor

class Person{ class Student7{


void message() { int no;
System.out.println("7"); System.out.println("7"); String name;
} Student7(){
no=66;
} name="abc";
s Student extends Person{ class Student extends Person{ }
void message() { void message() { Student7(int n,Strin
System.out.println("8"); System.out.println("89"); no=n;
} name=a;
Student() { void display() { }
super(); message(); void display(){
message(); super.message(); System.out.println(
} }
} }
ass ExampleCc { public class ExampleCc { public class Sample{
ic static void main(String args[]) { public static void main(String args[]) { public static void main
Student s=new Student(); Student s=new Student(); Student7 s1=new Stud
s.message(); Student7 s2=new Stud
} s1.display();
} s2.display();
}
}
Constructor overloading: class Bank{
static int getROI(){
class Student7{ return 0;
int no; }
String name; }
Student7(){ class Hdfc extends Bank{
no=66; static int getROI(){
name="abc"; return 7;
}
Student7(int n,String a){ }
class Andhra{
name=a; static int getROI(){
return 8;
void display(){ }
System.out.println(no+" "+name); }
class Sbi{
static int getROI(){
public class Sample{ return 9;
public static void main(String args[]){ }
Student7 s1=new Student7(); }
Student7 s2=new Student7(56,"cde");
s1.display(); public class Test {
s2.display(); public static void main(String args[]) {
Hdfc h=new Hdfc();
Andhra a=new Andhra();
Sbi s=new Sbi();
System.out.println(h.getROI()+" "+a.getROI()+" "+s.getROI())
}
}
int getROI(){

main(String args[]) {

w Andhra();

intln(h.getROI()+" "+a.getROI()+" "+s.getROI());


method
In a Class Same Name Different
method Parameters

method
By Changing No.of Arguments
ways to Overload Method
By Changing DataTypes

Example1

package overload;

class Sum1
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}

public class TestOL


{
public static void main(String args[])
{

System.out.println(Sum1.add(10,10));
System.out.println(Sum1.add(15,15,15));
}
}

Method Overriding
If subclass(child class) has the same method as declared in parent class

subclass method same as parentclass

Usage of Java Method Overriding


To provide specific implementation of a method already provided by its
*RunTime Polymorphism

Rules
methods must have same name as in parent class
methods must have same parameter as in parent class

Difference between Overloading and Overriding


Overloading Overriding

provide specific implementation of metho


To improve readability of program
that is already provided by its parent clas

Occurs in Two Classes that have IS-A


performed within class
relationship inheritance
parameter must be different parameter must be same
Ex: Complie Time Polymorphism Ex:Runtime polymorphism

Example

package overload;

class Bank //parent class


{
int getROI()
{
return 0;
}
}
class Andhra extends Bank
{
int getROI()
{
return 8;
}
}
class HDFC extends Bank
{
int getROI()
{
return 7;
}
}
class SBI extends Bank
{
int getROI()
{
return 9;
}
}
public class TestBank
{
public static void main(String args[])
{
Andhra a=new Andhra();
HDFC h=new HDFC();
SBI sb=new SBI();
System.out.println("Andhra ROI="+a.getROI());
System.out.println("HDFC ROI="+h.getROI());
System.out.println("SBI ROI="+sb.getROI());
}
}
Method Overloading

Example 2
method
OverLoading package overload;

class Sum2
{
static int add(int a,int b)
{
return a+b;
}
static double add(double a,double b,double c)
{
return a+b+c;
}
}

public class TestOL1


{
public static void main(String args[])
{

System.out.println(Sum2.add(10,10));
System.out.println(Sum2.add(15.1,15.1,15.1));
}
}

Example 1 for Method Overriding

package overload;

class College47
{
void admit()
{
System.out.println("get admission"
Method Overriding }
}
d in parent class method overriding in Java

public class Branch extends College47


{
public static void main(String args[])
d already provided by its superclass {
Branch objor=new Branch();//instance to ch
objor.admit();// calling method with child cl
}
}
get admission

riding
Overriding

implementation of method
rovided by its parent class

o Classes that have IS-A


nship inheritance
ter must be same
time polymorphism
Bank

getROI:Int

Andhra HDFC SBI

getROI:Int getROI:Int getROI:Int

TestBank
main:String

Method overloading is the process that can create multiple


methods of the same name in the same class, and all the methods
work in different ways. Method overloading occurs when there is
more than one method of the same name in the class.

Method overriding is the process when the subclass or a


child class has the same method as declared in the parent
class.

getROI());
Method overloading allows the method to have
the same name which differs on the basis of
arguments or the argument types. It can be
related to compile-time polymorphism.

The main advantage of using method overloading in Java is that it gives us


the liberty to not define a function again and again for doing the same
thing. In an example, the two methods are basically performing division, so
we can have different methods with the same name but with different
d(15.1,15.1,15.1)); parameters. It also helps in compile-time polymorphism.

thod Overriding Example 2 for Method Overriding

package overload;

class College471 //parent class


{
void admit() //define method
out.println("get admission"); {
System.out.println("get admission");
}
}
//create child class
College47 public class Branch1 extends College471
{
main(String args[]) void admit()
{
Branch();//instance to child class System.out.println("select Branch");
alling method with child class instance. }
public static void main(String args[])
{
dmission Branch1 objor1=new//creating object;
objor1.admit(); //calling method
}
}
select Branch

Inheritance in java involves a relationship between parent and child classes.


Whenever both the classes contain methods with the same name and arguments or
parameters it is certain that one of the methods will override the other method
during execution. The method that will be executed depends on the object.

If the child class object calls the method, the child class method will override the
parent class method. Otherwise, if the parent class object calls the method, the
parent class method will be executed.

Method overriding also helps in implementing runtime polymorphism in java

SBI

getROI:Int
Method Overloading
class Div
{
public static int div(int a ,int b)
{
return (a/b);
}
public static int div(int a,int b,int c)
{
return ((a+b)/c);
}

}
public class Division
{
public static void main(String args[])
{

System.out.println(Div.div(10,2));
System.out.println(Div.div(10,2,3));

}
}

we have two methods with the same name


but different parameters. This is how the
method overloading
constructor overloading

class Demo{
int value1;
int value2;
Demo()
{
this(3);
}
Demo(int a)
{
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display()
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
}
public class Test
{
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Inside 2nd Constructor
Inside 2nd Constructor
Inside 3rd Constructor
Value1 === 3
Value2 === 0
Value1 === 30
Value2 === 0
Value1 === 30
Value2 === 40
Method Overriding
class Day
{

public void hour()


{
System.out.println("Iam in DS Class");
}
}

class Section extends Day {

public void hour()


{
System.out.println("Iam in MFE Class");
}
}
public class Student
{

public static void main(String args[])


{
Day a = new Day(); // Day reference and object
Day b = new Section(); // Day reference but Section object

a.hour();// runs the method in Day class


b.hour();// Runs the method in Section class
}
}

Here we two methods named as hour in class Day and class Section

Output

Iam in DS Class
Iam in MFE Class

Rules for Method Overriding


Method must have same name and same parameter as in Parent class
There must be an IS-A relationship(Inheritance)

constructor overriding can't be done


No , constructor can never be overridden . It's
because constructor acts at class level and it's
unique for each class created in Java 
Method Overriding
class Day
{

public void hour()


{
System.out.println("Iam in DS Class");
}
}

class Section extends Day {

public void hour()


{
super.hour();
System.out.println("Iam in MFE Class");
}
}
public class Student
{

public static void main(String args[])


{
Day a = new Day(); // Day reference and object
Day b = new Section(); // Day reference but Section object

a.hour();// runs the method in Day class


b.hour();// Runs the method in Section class
}
}

Here we two methods named as hour in class Day and class Section and we are
making use of super keyword
Output

Iam in DS Class
Iam in DS Class
Iam in MFE Class
Method Overriding

class One {
int num;
One(int n) {
this.num = n;
}
void show() {
System.out.println ("num" +num);
}
}
class Two extends One {
int num1;
Two(int x, int y) {
super(x);
num1 = y;
}
void show() {
System.out.println("sub class number"+num1);
System.out.println("super class number"+num);
super.show();
}
}
public class SampleClass {
public static void main(String args[ ]) {
Two t = new Two(100,200);
t.show();
}
}

Explaination

Program defines a class SimpleClass. It creates an object of


class Two which extends the class One. The class One has
Output only one constructor, which assigns the value
sub class number200 of n to num. The class Two has an additional instance variable
super class number100 (y in this example) and defines a constructor to
initialize x and y. The constructor defined in the program
num100
calls the constructor method belonging to class One to
initialize the instance variable x of class Two.
creates an object of
. The class One has
gns the value
onal instance variable
constructor to
ned in the program
ng to class One to
of class Two.
Objects as Parameters
A method can take an objects as a parameter. For example, in the following program, the method se
three parameter. The first parameter is an Data object. If you pass an object as an argument
the mechanism that applies is called pass-by-reference, because a copy of the reference cont
variable is transferred to the method, not a copy of the object itself.

package Array;

public class JObject {


public static void main(String args[])
{
Data da=new Data();
SetData sd=new SetData();
sd.setData(da,50,100);
sd.getData(da);
}
}
class Data
{
int data1;
int data2;
}
class SetData{
void setData(Data da,int d1,int d2)
{
da.data1=d1;
da.data2=d2;
}
void getData(Data da)
{
System.out.println("data :"+da.data1);
System.out.println("data :"+da.data2);
}
}

package Array; Returning Objects

public class RectDemo


{
public static void main(String args[])
{
Rect r1=new Rect(10,20);
r1.area(r1);
}
}
class Rect
{
int length,width;
Rect(int l,int w)
{
length=l;
width=w;
}
void area(Rect r)
{
int a=r.length*r.width;
System.out.println("area"+a);
}
}
wing program, the method setData( ) takes
an object as an argument to a method,
a copy of the reference contained in the
of the object itself.

package Array;

public class DemoTest


{
public static void main(String args[])
{
Demo d1=new Demo(10,20);
Demo d2=new Demo(10,20);
Demo d3=new Demo(-1,-2);
System.out.println("d1==d2"+d1.equalTo(d2));
System.out.println("d1==d3"+d1.equalTo(d3));
}
}
class Demo
{
int a,b;
Demo(int i,int j)
{
this.a=j;
this.b=j;
}
boolean equalTo(Demo d)
{
if(d.a==a&&d.b==b)
return true;
else
return false;
}
}

Returning Objects
In Java a method can return anytype of data including objects
package Array;

public class RectDemo1


{
public static void main(String args[])
{
Rect1 r1=new Rect1(10,20);
Rect1 r2;
r2=r1.getRec();
System.out.println("r1 length"+r1.length);
System.out.println("r1 length"+r1.width);
}
}
class Rect1
{
int length,width;
Rect1(int l,int w)
{
this.length=l;
this.width=w;
}
Rect1 getRec()
{
Rect1 r=new Rect1(10,20);
return r;
}
}
Array of Reference Variables

An array also consists of "boxes". You can put something


(an element) into each box. To access an element, you need
to know its box number (index).

Array Creation

public class Main {

public static void main(String[] args) {

String [] birthdays = new String[10];

}
}

Length of Array

public class Main {

public static void main(String[] args) {

String birthdays [] = new String[10];


birthdays[0] = "Jana Russell, March 12";
birthdays[1] = "Landon Chan, May 18";
birthdays[7] = "Rosie Mills, January 3";

String rosieBirthday = birthdays[7];


System.out.println(rosieBirthday);
}
}

public class Main {

public static void main(String[] args) {

String birthdays [] = new String[10];


birthdays[0] = "Jana Russell, March 12";
birthdays[1] = "Landon Chan, May 18";
birthdays[2] = "Jeremiah Leonard, July 12";
birthdays [3] = "Kenny Russo, September 7";
birthdays[4] = "Tommie Barnes, November 9";
birthdays [5] = "Roman Baranov, August 14";
birthdays [6] = "Chanice Andersen, April 1";
birthdays[7] = "Rosie Mills, January 3";
birthdays [8] = "Keenan West, October 19";
birthdays [9] = "Abraham McArthur, May 3";

for (int i = 0; i < birthdays.length; i++) {


System.out.println(birthdays[i]);
}
}
}
2 ways to create Array
String [] birthdays = new String[10];
String birthdays [] = new String[10];

Assigning Values into Array

public class Main {

public static void main(String[] args) {

String birthdays [] = new String[10];


birthdays[0] = "Jana Russell, March 12";
}
}

Length of Array

public class Main {

public static void main(String[] args) {

String birthdays [] = new String[10];


birthdays[0] = "Jana Russell, March 12";
birthdays[1] = "Landon Chan, May 18";
birthdays[7] = "Rosie Mills, January 3";

int birthdaysLength = birthdays.length;


System.out.println(birthdaysLength);
}
}

package Array;

import java.util.Scanner;

class Student9 voter


{
int sno; id name age
String sname;
public void storeData(int no,String name)
{
sno=no; voterdemo
sname=name;
}
public String displayData()
{
String result;
result=String.format("sno=%d,sname=%s", sno,sname);
return result;
}
}
public class MainMenu
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Student9 s[]=new Student9[10]; 10 records
int count=0;
boolean repeat=true;
int i,choice;
while(repeat)
{
System.out.println("1.New Details 2.Display Details 3.Searching 4.Exit");
System.out.println("enter choice");
choice=sc.nextInt();
if(choice==1)
{
s[count]=new Student9();
System.out.println("enter sno and sname");
int no=sc.nextInt();
String sname=sc.next();
s[count].storeData(no,sname);
count++;
}
else if(choice==2)
{
for(i=0;i<count;i++)
{
System.out.println(s[i].displayData());
}
}
else if(choice==3)
{
System.out.println("enter sno to search");
int no=sc.nextInt();
int search=0;
for(i=0;i<count;i++)
{
if(no==s[i].sno)
{
System.out.println("record exists");
System.out.println(s[i].displayData());
search=1;
break;
}
}
if(search==0)
System.out.println("Record does not exists");
}
else if(choice==4)
repeat=false;
}
}
}
3.Searching 4.Exit");
rd exists");
splayData());

not exists");
Passing and Returning Objects in Java

Java Pass by Value Object method reference type

step 1.) Create reference objects


step 2.) acts as if they are passed to methods by use of call by reference.
step 3.) Change to object inside method do reflect in the object as an argument.

objects to methods(as arguments)

package Array;

public class DemoTest


{
public static void main(String args[])
{
Demo d1=new Demo(10,20);
Demo d2=new Demo(10,20);
Demo d3=new Demo(-1,-2);
System.out.println("d1==d2"+d1.equalTo(d2));
System.out.println("d1==d3"+d1.equalTo(d3)); 1.)
}
}
class Demo
{
int a,b;
Demo(int i,int j) 2.)
{
this.a=j;
this.b=j;
}
boolean equalTo(Demo d)
{
if(d.a==a&&d.b==b)
return true;
else
return false;
}
}

Pass by Value
method parameter values are copied to another variable and then
copied

Pass by Reference

An Alias or reference to the actual parameter is passed to method

Example of call by value in java

package Array;

public class Operation {


int data=50;

void change(int data){


data=data+100;//changes will be in the local variable only
}

public static void main(String args[]){


Operation op=new Operation();

System.out.println("before change "+op.data);


op.change(500);
System.out.println("after change "+op.data);

}
}
Call by Reference

package Array;

public class CalRef


{
public static void main(String args[])
{
CallbyRef object=new CallbyRef(10,20);
System.out.println("value of a"+object.a);
System.out.println("value of a"+object.b);

object.change(object);
System.out.println("value of a"+object.a);
System.out.println("value of a"+object.b);
}
}
class CallbyRef
{
int a,b;
CallbyRef(int x,int y)
{
this.a=x;
this.b=y;
}
void change(CallbyRef obj)
{
obj.a+=10;
obj.b+=20;
}
}
Example 3

package Array;
public class JObject {
public static void main(String args[])
{
Data da=new Data();
SetData sd=new SetData();
sd.setData(da,50,100);
sd.getData(da);
}
}
class Data
{
int data1;
int data2;
}
class SetData
{
void setData(Data da,int d1,int d2)
{
da.data1=d1;
da.data2=d2;
}
void getData(Data da)
{
System.out.println("data :"+da.data1);
System.out.println("data :"+da.data2);
}
}
Array of Reference-Example2

package Array;

import java.util.Scanner;

class Student9
{
int sno;
String sname;
public void storeData(int no,String name)
{
sno=no;
sname=name;
}
public String displayData()
{
String result;
result=String.format("sno=%d,sname=%s", sno,sname);
return result;
}
}
public class MainMenu
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Student9 s[]=new Student9[10];
int count=0;
boolean repeat=true;
int i,choice;
while(repeat)
{
System.out.println("1.New Details 2.Display Details 3.Sea
System.out.println("enter choice");
choice=sc.nextInt();
if(choice==1)
{
s[count]=new Student9();
System.out.println("enter sno and sname");
int no=sc.nextInt();
String sname=sc.next();
s[count].storeData(no,sname);
count++;
}
else if(choice==2)
{
for(i=0;i<count;i++)
{
System.out.println(s[i].displayData());
}
}
else if(choice==3)
{
System.out.println("enter sno to search");
int no=sc.nextInt();
int search=0;
for(i=0;i<count;i++)
{
if(no==s[i].sno)
{
System.out.println("record exis
System.out.println(s[i].displayD
search=1;
break;
}
}
if(search==0)
System.out.println("Record does not exi
}
else if(choice==4)
repeat=false;
}
}
}
an argument. d

null

d1 d2 d3

a 10 a 10 a -1
b 20 b 20 b -2

NOTE
When equalTo() is called with d1 then d will point d2 Demo.equalTo() is
called by d1 by object
passing the parameter of d object
if(d.a==a&&d.b==b)
10==10 20==20 1

When equalTo() is called by d1 and d3 is passed an object


if(d.a==a&&d.b==b)

0
Another Example of call by value in java

In case of call by reference original value is changed if we made changes in the


called method. If we pass object in place of any primitive value, original value will
be changed. In this example we are passing object as a value

package Array;

public class Operation1 {

int data=50;

void change(Operation1 op){


op.data=op.data+100;//changes will be in the instance variable
}

public static void main(String args[]){


Operation1 op=new Operation1();

System.out.println("before change "+op.data);


op.change(op);//passing object
System.out.println("after change "+op.data);

}
}
Example1

package Array;

public class RectDemo


{
public static void main(String args[])
{
Rect r1=new Rect(10,20);
r1.area(r1);
}
}
class Rect
{
int length,width;
Rect(int l,int w)
{
length=l;
width=w;
}
void area(Rect r)
{
int a=r.length*r.width;
System.out.println("area"+a);
}
}
Example 2

package Array;

public class RectDemo1


{
public static void main(String args[])
{
Rect1 r1=new Rect1(10,20);
Rect1 r2;
r2=r1.getRec();
System.out.println("r1 length"+r1.length);
System.out.println("r1 length"+r1.width);
}
}
class Rect1
{
int length,width;
Rect1(int l,int w)
{
this.length=l;
this.width=w;
}
Rect1 getRec()
{
Rect1 r=new Rect1(10,20);
return r;
}
}

e2
sno,sname);

2.Display Details 3.Searching 4.Exit");

r sno and sname");


ln(s[i].displayData());

r sno to search");

out.println("record exists");
out.println(s[i].displayData());

ln("Record does not exists");


he instance variable
INNER CLASSES

There are four types of inner classes: member, static


member, local, and anonymous.

A member class is defined at the top level of the class. It may


have the same access modifiers as variables (public, protected,
package, static, final), and is accessed in much the same way
as variables of that class.

public class OuterClass {


int outerVariable = 100;

class MemberClass {
int innerVariable = 20;

int getSum(int parameter) {


return innerVariable + outerVariable + parameter;
}
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
MemberClass inner = outer.new MemberClass();
System.out.println(inner.getSum(3));
outer.run();
}

void run() {
MemberClass localInner = new MemberClass();
System.out.println(localInner.getSum(5));
}
}

* A static member class is defined like a member class, but with the keyword static.

package InnerClass;
public class OC2 {
// int outerVariable = 100;
static int staticOuterVariable = 200;

static class StaticMemberClass {


int innerVariable = 20;

int getSum(int parameter) {


// Cannot access outerVariable here
return innerVariable + staticOuterVariable + parameter;
}
}

public static void main(String[] args) {


OC2 outer = new OC2();
StaticMemberClass inner = new StaticMemberClass();
System.out.println(inner.getSum(3));
outer.run();
}

void run() {
StaticMemberClass localInner = new StaticMemberClass();
System.out.println(localInner.getSum(5));
}
}
A local inner class is defined within a method,
and the usual scope rules apply to it. It is only
accessible within that method, therefore
access restrictions (public, protected, package)
do not apply.
Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent o

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

For Method Overriding (so runtime polymorphism can be achieved).


For Code Reusability.

Class: A class is a group of objects which have common properties


Sub 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/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.

class Subclass-name extends Superclass-name  
{  
   //methods and fields  

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
single, multilevel and hierarchical.

Example1

package inherit;

class Employee7
{
float salary=40000;
}
public class Programmer extends Employee7
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Example 3 MultiLevel Inheritance

package inherit;

class CollegeM
{
void admission()
{
System.out.println("get Admitted");
}
}
class StudentM extends CollegeM
{
void branch()
{
System.out.println("Select Branch");
}
}
class SemM extends StudentM
{
void result()
{
System.out.println("passed");
}
}

public class MultiInherit


{
public static void main(String args[])
{
SemM sm=new SemM();
sm.result();
sm.branch();
sm.admission();
}
}
Example 5

package inherit;

class StudentY20
{
int year=2021;
String collegename="KLU";
void does()
{
System.out.println("Studying");
}
}
public class Student2021 extends StudentY20
{
String branch="CSE";
public static void main(String args[])
{
Student2021 s2021=new Student2021();
System.out.println(s2021.collegename);
System.out.println(s2021.year);
System.out.println(s2021.branch);
s2021.does();
}
}
ritance

s and behaviors of a parent object.

ld relationship.

chieved).

When one class inherits multiple classes, it is known as multiple inheritance. For Example:
ss. It is also called a

class inherits the


ss.

cilitates you to reuse


ass. You can use the
class.

Example 2 Single Inheritance

package inherit;
class Office
{
t derives from an void admission()
nctionality. {
System.out.println("get admitted");
}
}
class Student1 extends Office
{
void branch()
{
System.out.println("select branch");
}

ds Employee7 }
public class College7 {
public static void main(String args[])
{
Student1 s=new Student1();
s.admission();
mer salary is:"+p.salary); s.branch();
f Programmer is:"+p.bonus); }
}

Example 4 Hierarchical Inheritance

package inherit;

class CollegeH
{
void admission()
{
System.out.println("get Admitted");
}
}
class StudentH extends CollegeH
{
void branch()
{
System.out.println("Select Branch");
}
}
class RollH extends CollegeH
{
void no()
{
System.out.println("get Reg.NO");
}
}

public class HierarInherit


{
public static void main(String args[])
{
RollH rh=new RollH();
rh.no();
rh.admission();
}
}
private members can only be accessed using public or protected getter and setter
methods of super class

Example 6

package inherit;

class StudentY20E
{
private int year;
private String collegename;

public void setYear(int pyear)


{
this.year=pyear;
}
public int getYear()
{
return year;
}

public void setCollegeName(String pcollegename)


{
this.collegename=pcollegename;
}
public String getCollegeName()
{
return collegename;
}

void does()
{
System.out.println("Studying");
}
}
public class Student2021E extends StudentY20E
{
String branch="CSE";
public static void main(String args[])
{
Student2021 s2021=new Student2021();
System.out.println(s2021.collegename);
System.out.println(s2021.year);
System.out.println(s2021.branch);
s2021.does();
}
}
le inheritance. For Example:
Wrapper Classs
Mechanism to convert primitive into object and from object into primitive.
Autoboxing
The automatic conversion of primitive into object.
Unboxing
The conversion of object to primitive.

Autoboxing
package wrapclass;

public class WrapperClass


{
public static void main(String args[])
{
int a=20;
Integer i=Integer.valueOf(a);
Integer j=a;
System.out.println("a="+a);
System.out.println("i="+i);
System.out.println("j="+j);

}
}

Uses of Wrapper Class


Collections
Java Objects Serialization
Synchronization

1.) Change Value in method Call by Value


primitive donot change original value
pass
value object changes original value

2.) Serilaization Streams


3.) Synchronization multithreading
4.) java util package objects
5.) Collection FrameWorks
Objects AL
LL
Vector
QQ
Unboxing
package wrapclass;

public class WrapperClass1 {


public static void main(String args[])
{

Integer a=new Integer(3);


int i=a.intValue();
int j=a.intValue();
System.out.println("a="+a);
System.out.println("i="+i);
System.out.println("j="+j);
}

8 Classes of Java .lang packages are known as Wrapper Classes in Java

Primitive Type Wrapper Class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Wrapper Class Example
package wrapclass;

public class WrapperExample


{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
float f=50.0F;
boolean b1=true;
char c='a';
long l=40;
double d=60.0D;
//Wrapper Class
Byte byteobj=b;
Boolean booleanobj=b1;
Short shortobj=s;
Character charobj=c;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;

System.out.println("ByteObject="+byteobj);
System.out.println("BooleanObject="+booleanobj);
System.out.println("ShortObject="+shortobj);
System.out.println("CharacterObject="+charobj);
System.out.println("IntegerObject="+intobj);
System.out.println("LongObject="+longobj);
System.out.println("FloatObject="+floatobj);
System.out.println("DoubleObject="+doubleobj);

byte byteValue=byteobj;
short shortValue=shortobj;
int intValue=intobj;
long longValue=longobj;
float floatValue=floatobj;
double doubleValue=doubleobj;
char charValue=charobj;
boolean boolValue=booleanobj;

System.out.println("ByteValue="+byteValue);
System.out.println("BooleanValue="+boolValue);
System.out.println("ShortValue="+shortValue);
System.out.println("CharacterValue="+charValue);
System.out.println("IntegerValue="+intValue);
System.out.println("LongValue="+longValue);
System.out.println("FloatValue="+floatValue);
System.out.println("DoubleValue="+doubleValue);

}
}
Association
Association is a relationship between two separate classes which establishes thr

These relationships can be of four types: One-to-One relation 1 to 1

One-to-many relation 1 -M Dept

Prof Dept

Dept
Association
2 forms

Aggregation Composition

Has A relationship

Aggregation

Having their own relationship


means that destroying one object
will not affect another object

Example 1:

class Address
{
String city, state, country;
int pinCode;

Address(String city, String state, String country, int pinCode)


{
this.city = city;
this.state = state;
this.country = country;
this.pi
}
}

public class Student


{
String name;
int rollNo;
Address add; // Aggregration Creation
Student(String n, int r, Address a) // Aggregration as Argument
{
this.rollNo = r;
this.name = n;
this.add=a;
}
void display()
{
System.out.println("Name: " +name + ", "+"Roll no: " +rollNo);
System.out.println("Address:");
System.out.println(add.city+" "+add.state+" "+add.country+ " " +add.pinCode);
System.out.println("\n");
}
public static void main(String[] args)
{
Address a1 = new Address("Dhanbad,","Jharkhand,","India,", 826001);
Address a2 = new Address("Ranchi,","Jharkhand,","India,", 825001);

Student st1 = new Student("Deep", 05, a1); // Aggregation Invocation


Student st2 = new Student("John", 02, a2);

st1.display();
st2.display();
}
}
Example of aggregating relationship is “A student has an address”. A student has many pieces
of information such as name, roll no, email id, etc. It also contains one more important object
named “address” that contains information such as city, state, country, zip code.

Student class has an object of Address class where the address object contains its own
information such as city, state, country, etc. This relationship is Student Has-A address and is
called aggregation

Composition
more restrictive and strong form of aggregation. child object does not have its own lifetime.
object will also be destroyed. The child obje
parent object. Composition can be defined as
the child object cannot exist on its own witho
called compo

class Engine
{
String type;
int horsePower;
Engine(String type, int horsePower)
{
this.type = type;
this.horsePower = horsePower;
}
public String getType()
{
return type;
}
public int getHorsePower()
{
return horsePower;
}
}
class Car
{
String name;
Engine en; // Composition.

Car(String n, Engine e)
{
this.name = n;
this.en = e;
}
public String getName()
{
return this.name;
}
public Engine getEngine()
{
return this.en;
}
}

public class Test


{
public static void main(String[] args)
{
// Creating an object of Engine class.
Engine engn = new Engine("Petrol", 300);

// Creating an object of Car class.


Car car = new Car("Alto", engn);
System.out.println("Name of car: " +car.getName()+ "\n" +"Type of engine: " +
engn.getType()+ "\n" + "Horse power of Engine: " +engn.getHorsePower());
}
}
Aggregation Example

class Employees
{
String name;
int id ;
String dept;
Employees(String name, int id, String dept)
{
this.name = name;
this.id = id;
this.dept = dept;
System.out.println("Employee name is "+name+" Id is "+id+" Department is "+dept
}
}
class Department
{
String name, employees;
Department(String name, String employees)
{
this.name = name;
this.employees = employees;
}
}
class Organization
{
String officeName,departments;
Organization(String officeName, String departments)
{
this.officeName = officeName;
this.departments = departments;
}
}
public class AggregationDemo{
public static void main (String[] args)
{
Employees s1 = new Employees("Mia", 1, "Sales");
Employees s2 = new Employees("Priya", 2, "Marketing");
Employees s3 = new Employees("John", 1, "IT");
Employees s4 = new Employees("Rahul", 2, "Designing");
}
}

Output:
Employee name is Mia Id is 1 Department is Sales
Employee name is Priya Id is 2 Department is Marketing
Employee name is John Id is 1 Department is IT
Employee name is Rahul Id is 2 Department is Designing
Association
which establishes through their objects

Prof Dept Many-to-Many relation

Many-to-one relation M - 1 Prof


object

Prof Dept

Prof commun
icates

to use functionalities and


services provided by
them.
Example 2:

class Radius Example 3:


{
double r; class Calculation
Radius(double r) {
{ int calArea(int length, int brea
this.r=r*r; {
} return (length * breadth);
} }
}
public class Circle class Rectangle
{ {
double pi; Calculation c; // Use of Aggreg
Radius r; // Use of Aggregation. int area(int length, int breadth
Circle(double pi,Radius r1) {
{ c = new Calculation();
this.pi=pi; int areaRec = c.calArea(length
r=r1; return areaRec;
} }
void display() }
{ public class Test
System.out.println(2*r.r*pi); {
} public static void main(String
public static void main(String[] args) {
{ Rectangle rec = new Rectang
Radius r=new Radius(4); int result =rec.area(25,60
Circle c=new Circle(3.14,r); System.out.println("Area o
c.display(); }
Argument } Aggregration as Argument }
}

Invocation
not have its own lifetime. If the parent object is destroyed, the child
destroyed. The child object cannot exist without the existence of its
position can be defined as if a parent object contains a child object and
nnot exist on its own without having the existence of parent object, it is
called composition in java.
Aggregation Example

import java.io.*;
import java.util.*;
class stud_class
{
String stud_name;
int roll_no ;
String stud_dept;
stud_class(String stud_name, int roll_no, String stud_dept)
{
Department is "+dept); this.stud_name = stud_name;
this.roll_no = roll_no;
this.stud_dept = stud_dept;
}
}
class Depofcollege
{
String stud_name;
private List<stud_class> students;
Depofcollege(String stud_name, List<stud_class> students)
{
this.stud_name = stud_name;
this.students = students;
}
public List<stud_class> getStudentsDetails()
{
return students;
}
}
class college
{
String collegeName;
private List<Depofcollege> departments;
college(String collegeName, List<Depofcollege> departments)
{
this.collegeName = collegeName;
this.departments = departments;
}
public int totalstudents()
{
int noOfStudents = 0;
List<stud_class> students;
for(Depofcollege dept : departments)
{
students = dept.getStudentsDetails();
for(stud_class s : students)
{
noOfStudents++;
}
}
return noOfStudents;
}
}
public class aggregation
{
public static void main (String[] args)
{
stud_class stud1 = new stud_class("Sameer", 5, "IT");
stud_class stud2 = new stud_class("Pooja", 6, "IT");
stud_class stud3 = new stud_class("Sanddep", 8, "Mech");
stud_class stud4 = new stud_class("Jenny", 2, "Mech");
List <stud_class> i_students = new ArrayList<stud_class>();
i_students.add(stud1);
i_students.add(stud2);
List <stud_class> me_students = new ArrayList<stud_class>();
me_students.add(stud3);
me_students.add(stud4);
Depofcollege IT = new Depofcollege("IT", i_students);
Depofcollege Mech = new Depofcollege("Mech", me_students);
List <Depofcollege> departments = new ArrayList<Depofcollege>();
departments.add(IT);
departments.add(Mech);
college college= new college("MIT", departments);
System.out.print("Count of students: ");
System.out.print(college.totalstudents());
}
}

Output
Count of students: 4
M-M Prof Dept

Prof Dept

Prof Dept

other
object

unctionalities and
ces provided by
them.

Area(int length, int breadth){

(length * breadth);

tion c; // Use of Aggregation.


a(int length, int breadth)

w Calculation();
aRec = c.calArea(length, breadth); // code reusability.
areaRec;
c static void main(String[] args)

angle rec = new Rectangle();


result =rec.area(25,60);
stem.out.println("Area of rectangle: " +result);
xample Composition Example

import java.io.*;
import java.util.*;
class Lib
{
public String name_book;
public String bk_author;
Lib(String name_book, String bk_author)
{
String stud_dept) this.name_book = name_book;
this.bk_author = bk_author;
}
}
class Library
{
private final List<Lib> Lib_books;
Library (List<Lib> Lib_books)
{
this.Lib_books =Lib_books;
}
_class> students) public List<Lib> book_details(){
return Lib_books;
}
}
public class composition
{
public static void main (String[] args)
{
Lib book1 = new Lib("Database management", "Ra
Lib book2 = new Lib("MySql", "Rajiv Chopra l");
Lib book3 = new Lib("oracle", "Donald Burleson");
List<Lib> Lib_books = new ArrayList<Lib>();
Lib_books.add(book1);
Lib_books.add(book2);
ege> departments) Lib_books.add(book3);
Library library = new Library(Lib_books);
List<Lib> bks = library.book_details();
for(Lib bk : bks){
System.out.println("name_book : " + bk.name_boo
+" bk_author : " + bk.bk_author);
}
}
}

Output:
name_book : Database management and bk_auth
name_book : MySql and bk_author : Rajiv Chopra
name_book : oracle and bk_author : Donald Burle

r", 5, "IT");
, 6, "IT");
ep", 8, "Mech");
", 2, "Mech");
st<stud_class>();
yList<stud_class>();

i_students);
ech", me_students);
rayList<Depofcollege>();
osition Example

class Engine
{
// starting an engine.
public void work()
{
System.out.println("Engine of car has been sta
tring bk_author) }
}
// Engine class
final class Car
{
// For a car to move,it need to have a engine.
private final Engine engine; // Composition
//private Engine engine; // Aggregation
Car(Engine engine)
{
this.engine = engine;
}
// car start moving by starting engine
public void move()
{
if(engine != null)
{
engine.work();
System.out.println("Car is moving ");
tring[] args) }
}
abase management", "Rajiv Chopra "); }
Sql", "Rajiv Chopra l"); public class Test
cle", "Donald Burleson"); {
ArrayList<Lib>(); public static void main (String[] args)
{
// making an engine by creating an instance of
Engine engine = new Engine();
rary(Lib_books); // Making a car with engine.so we are passing a
ok_details(); Car car = new Car(engine);
car.move();
_book : " + bk.name_book + " and "
}
}

anagement and bk_author : Rajiv Chopra


bk_author : Rajiv Chopra l
bk_author : Donald Burleson
gine of car has been started ");

need to have a engine.


gine; // Composition
gine; // Aggregation

starting engine

Car is moving ");


(String[] args)

creating an instance of Engine class.

ngine.so we are passing a engine instance as an argument while creating instace of Car.
Objects as Parameters
A method can take an objects as a parameter. For example, in the following program, the method se
three parameter. The first parameter is an Data object. If you pass an object as an argum
method,then the mechanism that applied is called pass-by-reference, because a copy of the
contained in the variable is transferred to the method, not a copy of the object itself

package Array;

public class JObject {


public static void main(String args[])
{
Data da=new Data();
SetData sd=new SetData();
sd.setData(da,50,100);
sd.getData(da);
}
}
class Data
{
int data1;
int data2;
}
class SetData{
void setData(Data da,int d1,int d2)
{
da.data1=d1;
da.data2=d2;
}
void getData(Data da)
{
System.out.println("data :"+da.data1);
System.out.println("data :"+da.data2);
}
}

package Array; Returning Objects

public class RectDemo


{
public static void main(String args[])
{
Rect r1=new Rect(10,20);
r1.area(r1);
}
}
class Rect
{
int length,width;
Rect(int l,int w)
{
length=l;
width=w;
}
void area(Rect r)
{
int a=r.length*r.width;
System.out.println("area"+a);
}
}
wing program, the method setData( ) takes
pass an object as an argument to a
rence, because a copy of the reference
ot a copy of the object itself.

package Array;

public class DemoTest


{
public static void main(String args[])
{
Demo d1=new Demo(10,20);
Demo d2=new Demo(10,20);
Demo d3=new Demo(-1,-2);
System.out.println("d1==d2"+d1.equalTo(d2));
System.out.println("d1==d3"+d1.equalTo(d3));
}
}
class Demo
{
int a,b;
Demo(int i,int j)
{
this.a=j;
this.b=j;
}
boolean equalTo(Demo d)
{
if(d.a==a&&d.b==b)
return true;
else
return false;
}
}

Returning Objects
In Java a method can return anytype of data including objects
package Array;

public class RectDemo1


{
public static void main(String args[])
{
Rect1 r1=new Rect1(10,20);
Rect1 r2;
r2=r1.getRec();
System.out.println("r1 length"+r1.length);
System.out.println("r1 length"+r1.width);
}
}
class Rect1
{
int length,width;
Rect1(int l,int w)
{
this.length=l;
this.width=w;
}
Rect1 getRec()
{
Rect1 r=new Rect1(10,20);
return r;
}
}
Polymorphism in Java is the task that performs a single action in different ways.
Java supports polymorphism
Polymorphism occurs when there is inheritance, i.e. there are many classes that are related to each other.

Inheritance is a powerful feature in Java. Inheritance lets one class acquire the properties
and attributes of another class. Polymorphism in Java allows us to use these inherited
properties to perform different tasks. Thus, allowing us to achieve the same action in many
different ways.

Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is class A
resolved at run time, rather than compile time. {
void m1()
When an overridden method is called through a superclass reference, {
Java determines which version(superclass/subclasses) of that method is System.out.println("Inside A'
1
to be executed based upon the type of the object being referred to at }
the time the call occurs. Thus, this determination is made at run time. }

At run-time, it depends on the type of the object being referred to (not class B extends A
2 the type of the reference variable) that determines which version of an {
overridden method will be executed // overriding m1()
void m1()
A superclass reference variable can refer to a subclass object. This {
3 is also known as upcasting. Java uses this fact to resolve calls to System.out.println("Inside B'
overridden methods at run time. }
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C'
}
}
public class Dispatch
{
public static void main(String
{

Therefore, if a superclass contains a method that is overridden by a


A a = new A(); // object of ty
subclass, then when different types of objects are referred to
B b = new B(); // object of ty
through a superclass reference variable, different versions of the
C c = new C();// object of typ
method are executed.
A ref; // obtain a reference
ref = a; // ref refers to an A
ref.m1(); // calling A's versi
ref = b; // now ref refers t
ref.m1(); // calling B's versio
ref = c; // now ref refers t
ref.m1(); // calling C's versio
}
}

Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Polymorphism in Java via two different methods: Compile-Time Polymorphism in Java is also known as Static Polymorphis
Compile-Time polymorphism is achieved through Method Overloading
1. Method Overloading
2. Method Overriding
Runtime polymorphism in Java is also popularly known as Dynamic Binding
Polymorphism in Java can be classified into two
Method Dispatch
types, i.e:

1. Static/Compile-Time Polymorphism
call to an overridden method is resolved dynamically at runtime rathe
2. Dynamic/Runtime Polymorphism
compile-time.This can be achieved by Runtime polymorphism via Method

Explanation :
The above program creates one superclass called A and
it’s two subclasses B and C. These subclasses overrides
m1( ) method.
m.out.println("Inside A's m1 method");

Inside the main() method in Dispatch class, initially objects of type A, B, and C ar
A a = new A(); // object of type A
1
B b = new B(); // object of type B
C c = new C(); // object of type C
rriding m1()

m.out.println("Inside B's m1 method");


rriding m1()

m.out.println("Inside C's m1 method");


Now a reference of type A, called ref, is also declared, initially it will point to nul
2
A ref; // obtain a reference of type A
ass Dispatch

static void main(String args[])

new A(); // object of type A


new B(); // object of type B Now we are assigning a reference to each type of object (either A’s or B’s or C’s)
new C();// object of type C 3 ref = a; // r refers to an A object
// obtain a reference of type A ref.m1(); // calling A's version of m1()
a; // ref refers to an A object
1(); // calling A's version of m1()
b; // now ref refers to a B object
1(); // calling B's version of m1()
c; // now ref refers to a C object
1(); // calling C's version of m1()
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()

ref = c; // now r refers to a C object


ref.m1(); // calling C's version of m1()
as Static Polymorphism
ethod Overloading

wn as Dynamic Binding or Dynamic

ically at runtime rather than at


ymorphism via Method Overriding.

Runtime Polymorphism with Data Members


In Java, we can override methods only, not the variables(data members), so run

Example

class A
{
of type A, B, and C are declared. int x = 10;
}

class B extends A
{
int x = 20;
}

public class Test


{
public static void main(String args[])
{
A a = new B(); // object of type B
// Data member of class A will be accessed
System.out.println(a.x);
}
}
ally it will point to null.

Output:
10

ither A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is deter
ta members), so runtime polymorphism cannot be achieved by data members

Explanation : In above program, both the class A(super class)


and B(sub class) have a common variable ‘x’. Now we make object
of class B, referred by ‘a’ which is of type of class A. Since
variables are not overridden, so the statement “a.x” will always
refer to data member of super class.

Advantages of Dynamic Method Dispatch

Dynamic method dispatch allow Java to support overriding of methods which


is central for run-time polymorphism.
It allows a class to specify methods that will be common to all of its
derivatives, while allowing subclasses to define the specific implementation
of some or all of those methods.

It also allow subclasses to add its specific methods subclasses to define the
specific implementation of some.

Static vs Dynamic binding


Static binding is done during compile-time while dynamic binding is done during run-time.

private, final and static methods and variables uses static binding and bonded by
compiler while overridden methods are bonded during runtime based upon type of
runtime object

) executed is determined by the type of object being referred to at the time of the call.

You might also like