CTOOD CO1 CO2 Notes
CTOOD CO1 CO2 Notes
Role of OS
Microsoft
MAC Linux
Windows
WebBrowser runs
ByteCodes
JVM
JVM
JDK
Java Development ToolKit
Complier JRE
Java RunTime Environment
Java ClassFile
input
JVM
Program BYTECODE
Output
Complier +
Java
compliation
class
bytecode
JVM
Output
History
Object
Simple Oriented
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
Complier + JRE
import implements classes and methods
JVM
imports package
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
variable declared
outside the m
variable declared
outside the m
Example 1:
access
specifier
Example 2:
}
}
Example 3:
}
}
OOPs (Object Oriented Programming System)
OOP
Way of Solving
Complex Program
t is an entity
gram has many objects which are used to solve real world entity
abstract
Hiding Data and shows only essential parts.
Hides the implementation details
Ex: Android PlayStore
.app .exe
Name Student
Variables name
Methods roll no
doj
read()
write()
play()
Variables
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
System.out.println("Hello Java");
method
class Addition
int x=10;
int y=25;
int z=x+y;
System.out.println("Sum of X+Y=",z);
class VarExample
Reads Data
from Keyword
Values
HardCore
Scanner
CommandLineArguments
Files
IO Streams(Bytes of Data)
System.out System.err
Assign
Read
Runtime
Files
1 2
Addition using hardcore values. Addition using scanner function.
(String args[])
Modularization
Method Modularization
* Dividing program into set of methods
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;
}
}
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
package gettersetter;
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;
package gettersetter;
class AmDemo
private int x;
public void setX(int x)
this.x=x;
return this.x;
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
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
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:
package myconstructor;
}
class Student7
this is Default parameterized
{ constructor
int sno;
String sname;
Student7() Here Construtor is Created
{
sno=457;
sname="Raj";
}
}
package myconstructor;
package myconstructor;
package myconstructor;
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;
}
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);
}
}
package myconstructor;
public BaseClass() {
//calling a three argument constructor of the same class
this("Male", "English", "1989/11/10");
System.out.println("I'm executed third!!!");
}
}
Constructor chaining example #1 – Constructors are chained using
this() keyword
package myconstructor;
String firstName;
String country;
int age;
public DerivedClass() {
// calling one argument constructor
this("Maggie");
}
void displayValues() {
System.out.println("First Name : " + firstName);
System.out.println("Country : " + country);
System.out.println("Age : " + age);
}
package myconstructor;
public DerivedClass7() {
//calling no argument constructor of the super class
super();
}
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);
} }
} }
main(String args[]) {
Super. keyword with methods Constructor
main(String args[]) {
w Andhra();
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;
}
}
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
Rules
methods must have same name as in parent class
methods must have same parameter as in parent class
Example
package overload;
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;
}
}
System.out.println(Sum2.add(10,10));
System.out.println(Sum2.add(15.1,15.1,15.1));
}
}
package overload;
class College47
{
void admit()
{
System.out.println("get admission"
Method Overriding }
}
d in parent class method overriding in Java
riding
Overriding
implementation of method
rovided by its parent class
getROI:Int
TestBank
main:String
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.
package overload;
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.
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));
}
}
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
{
Here we two methods named as hour in class Day and class Section
Output
Iam in DS Class
Iam in MFE 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
package Array;
package Array;
Returning Objects
In Java a method can return anytype of data including objects
package Array;
Array Creation
}
}
Length of Array
Length of Array
package Array;
import java.util.Scanner;
not exists");
Passing and Returning Objects in Java
package Array;
Pass by Value
method parameter values are copied to another variable and then
copied
Pass by Reference
package Array;
}
}
Call by Reference
package Array;
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
0
Another Example of call by value in java
package Array;
int data=50;
}
}
Example1
package Array;
package Array;
e2
sno,sname);
r sno to search");
out.println("record exists");
out.println(s[i].displayData());
class MemberClass {
int innerVariable = 20;
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;
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
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");
}
}
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
ld relationship.
chieved).
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
ss. It is also called a
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); }
}
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");
}
}
Example 6
package inherit;
class StudentY20E
{
private int year;
private String 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;
}
}
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
Prof Dept
Dept
Association
2 forms
Aggregation Composition
Has A relationship
Aggregation
Example 1:
class Address
{
String city, state, country;
int pinCode;
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;
}
}
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
Prof commun
icates
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.
(length * breadth);
w Calculation();
aRec = c.calArea(length, breadth); // code reusability.
areaRec;
c static void main(String[] args)
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 "
}
}
starting engine
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;
package Array;
Returning Objects
In Java a method can return anytype of data including objects
package Array;
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
{
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()
Example
class A
{
of type A, B, and C are declared. int x = 10;
}
class B extends A
{
int x = 20;
}
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
It also allow subclasses to add its specific methods subclasses to define the
specific implementation of some.
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.