SlideShare a Scribd company logo
Unit 2
Classes, Inheritance ,Packages &
Interfaces
procedure Oriented programming Object Oriented Programming
Divided Into In POP, program is divided into small
parts calledf unctions.
In OOP, program is divided into
parts called objects.
Importance In POP,Importance is not given
to data but to functions as well
as sequence of actions to be done.
(Algorithm)
In OOP, Importance is given to the
data rather than procedures or
functions because it works as a
real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access specifier. OOP has access specifiers named
Public, Private, Protected, etc.
Data Moving In POP, Data can move freely from
function to function in the system.
In OOP, objects can move and
communicate with each other
through member functions.
Data Access In POP, Most function uses Global
data for sharing that can be accessed
freely from function to function in the
system.
In OOP, data can not move easily
from function to function, it can
be kept public or private so we
can control the access of data.
Data Hiding POP does not have any proper way for
hiding data so it is less secure.
OOP provides Data Hiding so
provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in
the form of Function Overloading
and Operator Overloading.
Examples Example of POP are : C, VB, FORTRAN,
Pascal.
Example of OOP are : C++, JAVA,
VB.NET, C#.NET.
Class & Object
• CLASS : Represents the group of similar objects. A class binds the
data & its function together. It has 2 parts.
1.Class Definition –Member Data
2.Class function definitions- Member Functions
• An object is defined by a class
• A class is the blueprint of an object
• The class uses methods to define the behaviors of the object
• The class that contains the main method of a Java program
represents the entire program
• A class represents a concept, and an object represents the
embodiment of that concept
• Multiple objects can be created from the same class
Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or what can be done to it)
• The state of a bank account includes its account
number and its current balance
• The behaviors associated with a bank account
include the ability to make deposits and
withdrawals
• Note that the behavior of an object might change
its state. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
DIFFERENCE BETWEEN STRUCTURE
AND CLASS
STRUCTURE CLASS
Hold only one data contains both function & data
Data members are PUBLIC
by default
Members are PRIVATE by
default
Members are easily
accessible
Not easy to access
Donot support
inheritance
Supports inheritance
no such things Members of a class can be
Private, public & private also
• Constructors are used to set initial values for
the object's instance variables, and to perform
other actions that need to be done before the
object is used
How to Create Object in Java
• Using new Keyword
• Using clone() method
• Using newInstance() method of the Class
class
• Using newInstance() method of the
Constructor class
• Using Deserialization
SYNTAX
ClassName object = new ClassName();
public class Hello
{
int x = 5;
public static void main(String[] args)
{
Hello myObj = new Hello();
System.out.println(myObj.x);
}
}
public class Hello
{
int x = 5;
public static void main(String[] args)
{
Hello myObj1= new Hello();
Hello myObj2= new Hello();
System.out.println(myObj.x);
}
}
Naming conventions
ACCESS SPECIFIERS
• CLASS MEMBER VISIBILITY:
1. PRIVATE : The class members(functions &
data) as private can be access only within the
class.(By default its private only)
2 . PUBLIC : Can be accessed from outside the
class
3. PROTECTED: Used in inheritance.
Syntax to declare a class:
class <class_name>{
data member;
method;
}
Simple Example of Object and Class
class Student1{
int id; //data member (also instance variable)
String name; //data member(also instance variable)
void getId(); //member function
public static void main(String args[]){
Student1 s1=new Student1(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
s1.getId();
}
}
The new keyword is used to allocate memory at runtime.
The program shows an example to insert values in a record.
Advantage of Method
•Code Reusability
•Code Optimization
new keyword
class Student2{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{ System.out.println(rollno+" "+name); }
public static void main(String args[])
{
Student2 s1=new Student2();
Student2 s2=new Student2();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
} }
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String
args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's
instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to
mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width *
mybox1.height * mybox1.depth;
System.out.println("Volume is " +
vol);
// compute volume of second box
vol = mybox2.width *
mybox2.height * mybox2.depth;
System.out.println("Volume is " +
vol);
} }
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
double volume()
{
System.out.print("Volume is ");
return(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance
variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
vol=mybox1.volume();
System.out.println(vol);
// display volume of second box
vol=mybox2.volume();
System.out.println(vol);
}}
Constructors
• Constructor in java is a special type of method that
is used to initialize the object.
• Java constructor is invoked at the time of object
creation. It constructs the values i.e. provides data
for the object that is why it is known as
constructor.
Rules for creating java constructor
• Constructor name must be same as its class name
• Constructor must have no explicit return type, not
even void.
• Types of java constructors
There are 3 types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
• Copy constructor (object clone)
Default constructors
class Box
{ double width; double height;
double depth;
// This is the constructor for Box.
Box()
{ System.out.println("Constructing
Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{ return width * height * depth;
class BoxDemo6
{ public static void main(String args[])
{
// declare, allocate, and initialize Box
objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is "+ vol);
} }
Parameterized constructor
class Box
{ double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double
d)
{ width = w; height = h; depth =
d; }
// compute and return volume
double volume()
{ return width * height * depth;
class BoxDemo {
public static void main(String args[])
{
// declare, allocate, and initialize Box
objects
Box mybox1 = new Box(10, 20, 5);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " +
vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " +
vol);
Copy constructor
Previous program can be extended with passing object of the class
to the constructor itself.
Eg:
Box (Box b)
{
System.out.println(“cloning object”);
}
Public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 5);
Box mybox2 = new Box(mybox1);
//mybox2 is cloned from mybox1 object
}
}
Constructor with different arguments / different number of
arguments are called constructor overloading.
Java program to illustrate Constructor Overloading
class Box
{
double width, height, depth;
// constructor used when no dimensions specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// Main code
public class Test
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox2 = new Box();
Box mycube = new Box(7);
Box mybox1 = new Box(10, 20, 15);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}
Method Overloading
• If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
• Method overloading increases the readability of the
program.
• 2 ways to differentiate the methods which are
overloaded
1.by number of arguments
2.by data types
1)Example of Method Overloading by
changing the no. of arguments
class Calculation
{
void sum(int a,int b)
{System.out.println(a+b);}
void sum(int a,int b,int c)
{System.out.println(a+b+c);}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
} }
2)Example of Method Overloading by
changing data type of argument
class Calculation2
{
void sum(int a,int b)
{System.out.println(a+b);}
void sum(double a,double b)
{System.out.println(a+b);
}
public static void main(String args[]) {
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
} }
//Write a program to find area of geometrical
figures using method overloading.
import java.util.*;
class geofig
{
double area(double r)
{
return(3.14*r*r);
}
float area(float s)
{
return(s*s);
}
float area(float l,float b)
{
return(l*b);
}
double area(double b,double
h)
{ return(0.5*b*h);
public static void main(String arg[])
{
Scanner sc =new Scanner(System.in);
geofig g = new geofig();
System.out.println("enter the value for radius of
circle");
double r =sc.nextDouble();
System.out.println("area of circle="+g.area(r));
System.out.println("enter the value for side of a
square");
float s =sc.nextFloat();
System.out.println("area of square="+g.area(s));
System.out.println("enter the value for length and
breadth of rectangle");
float l =sc.nextFloat();
float b =sc.nextFloat();
System.out.println("area of rectangle="+g.area(l,b));
System.out.println("enter the value for base & height
of triangle");
double b1 =sc.nextDouble();
double h =sc.nextDouble();
System.out.println("area of triangle="+g.area(b1,h));
}
}
Lab 8:
import java.util.*;
class GarbageCollection
{ public static void main(String s[]) throws Exception
{ Runtime rs = Runtime.getRuntime();
System.out.println("Total memory is: " +
rs.totalMemory());
System.out.println("Free memory in JVM before
Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after
Garbage Collection = "+rs.freeMemory()); } }
Access Specifier
Java Command Line Arguments
• The java command-line argument is an
argument i.e. passed at the time of running
the java program.
• The arguments passed from the console can
be received in the java program and it can be
used as an input.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is:
"+args[0]);
}
}
keyword
final keyword
• The final keyword in java is used to restrict the
user. The java final keyword can be used in
many context
For example, when a variable is declared with the "final" keyword, its value
cannot be changed once it is set:
final int a = 10;
a = 20; // this will result in a compile-time error
the keyword "abstract" is used to
declare an abstract class or method.
Here's an example of an abstract class:
abstract class Shape { abstract double area();
}
• An abstract method is a method that is
declared in an abstract class, but does not
have a body. The purpose of an abstract
method is to specify a method signature that
must be implemented by any concrete
subclasses of the abstract class.
• Finalize Keyword in java:
• The finalize method in java is called by the
garbage collector before an object is garbage
collected.

More Related Content

Similar to Classes, Inheritance ,Packages & Interfaces.pptx

Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
secondakay
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
krismishra
 

Similar to Classes, Inheritance ,Packages & Interfaces.pptx (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Oop ppt
Oop pptOop ppt
Oop ppt
 
My c++
My c++My c++
My c++
 
C++ classes
C++ classesC++ classes
C++ classes
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
Class and object
Class and objectClass and object
Class and object
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Class and object
Class and objectClass and object
Class and object
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 

More from DivyaKS18 (11)

UNIX.ppt
UNIX.pptUNIX.ppt
UNIX.ppt
 
STORAGE MANAGEMENT AND PAGING ALGORITHMS.pptx
STORAGE MANAGEMENT AND PAGING ALGORITHMS.pptxSTORAGE MANAGEMENT AND PAGING ALGORITHMS.pptx
STORAGE MANAGEMENT AND PAGING ALGORITHMS.pptx
 
System calls in OS.pptx
System calls in OS.pptxSystem calls in OS.pptx
System calls in OS.pptx
 
PROCESS.pptx
PROCESS.pptxPROCESS.pptx
PROCESS.pptx
 
OS introduction.pptx
OS introduction.pptxOS introduction.pptx
OS introduction.pptx
 
exception -ppt.pptx
exception -ppt.pptxexception -ppt.pptx
exception -ppt.pptx
 
DES
DES DES
DES
 
monte carlo simulation
monte carlo simulationmonte carlo simulation
monte carlo simulation
 
mac-protocols
mac-protocols mac-protocols
mac-protocols
 
SMTP and TCP protocol
SMTP and TCP protocolSMTP and TCP protocol
SMTP and TCP protocol
 
Multithreading -Thread Fundamentals6.pptx
Multithreading -Thread Fundamentals6.pptxMultithreading -Thread Fundamentals6.pptx
Multithreading -Thread Fundamentals6.pptx
 

Recently uploaded

ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 

Classes, Inheritance ,Packages & Interfaces.pptx

  • 1. Unit 2 Classes, Inheritance ,Packages & Interfaces
  • 2. procedure Oriented programming Object Oriented Programming Divided Into In POP, program is divided into small parts calledf unctions. In OOP, program is divided into parts called objects. Importance In POP,Importance is not given to data but to functions as well as sequence of actions to be done. (Algorithm) In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach. Access Specifiers POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc. Data Moving In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. Data Access In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data can not move easily from function to function, it can be kept public or private so we can control the access of data. Data Hiding POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so provides more security. Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Examples Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.NET.
  • 3. Class & Object • CLASS : Represents the group of similar objects. A class binds the data & its function together. It has 2 parts. 1.Class Definition –Member Data 2.Class function definitions- Member Functions • An object is defined by a class • A class is the blueprint of an object • The class uses methods to define the behaviors of the object • The class that contains the main method of a Java program represents the entire program • A class represents a concept, and an object represents the embodiment of that concept • Multiple objects can be created from the same class
  • 4. Objects • An object has: – state - descriptive characteristics – behaviors - what it can do (or what can be done to it) • The state of a bank account includes its account number and its current balance • The behaviors associated with a bank account include the ability to make deposits and withdrawals • Note that the behavior of an object might change its state. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
  • 5.
  • 6. DIFFERENCE BETWEEN STRUCTURE AND CLASS STRUCTURE CLASS Hold only one data contains both function & data Data members are PUBLIC by default Members are PRIVATE by default Members are easily accessible Not easy to access Donot support inheritance Supports inheritance no such things Members of a class can be Private, public & private also
  • 7.
  • 8.
  • 9.
  • 10. • Constructors are used to set initial values for the object's instance variables, and to perform other actions that need to be done before the object is used
  • 11.
  • 12.
  • 13.
  • 14. How to Create Object in Java • Using new Keyword • Using clone() method • Using newInstance() method of the Class class • Using newInstance() method of the Constructor class • Using Deserialization
  • 15. SYNTAX ClassName object = new ClassName();
  • 16. public class Hello { int x = 5; public static void main(String[] args) { Hello myObj = new Hello(); System.out.println(myObj.x); } }
  • 17. public class Hello { int x = 5; public static void main(String[] args) { Hello myObj1= new Hello(); Hello myObj2= new Hello(); System.out.println(myObj.x); } }
  • 19.
  • 20. ACCESS SPECIFIERS • CLASS MEMBER VISIBILITY: 1. PRIVATE : The class members(functions & data) as private can be access only within the class.(By default its private only) 2 . PUBLIC : Can be accessed from outside the class 3. PROTECTED: Used in inheritance.
  • 21. Syntax to declare a class: class <class_name>{ data member; method; } Simple Example of Object and Class class Student1{ int id; //data member (also instance variable) String name; //data member(also instance variable) void getId(); //member function public static void main(String args[]){ Student1 s1=new Student1(); //creating an object of Student System.out.println(s1.id); System.out.println(s1.name); s1.getId(); } }
  • 22. The new keyword is used to allocate memory at runtime. The program shows an example to insert values in a record. Advantage of Method •Code Reusability •Code Optimization new keyword
  • 23. class Student2{ int rollno; String name; void insertRecord(int r, String n) { rollno=r; name=n; } void displayInformation() { System.out.println(rollno+" "+name); } public static void main(String args[]) { Student2 s1=new Student2(); Student2 s2=new Student2(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } }
  • 24. class Box { double width; double height; double depth; } class BoxDemo2 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } }
  • 25. // This program includes a method inside the box class. class Box { double width; double height; double depth; // display volume of a box double volume() { System.out.print("Volume is "); return(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box vol=mybox1.volume(); System.out.println(vol); // display volume of second box vol=mybox2.volume(); System.out.println(vol); }}
  • 26. Constructors • Constructor in java is a special type of method that is used to initialize the object. • Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Rules for creating java constructor • Constructor name must be same as its class name • Constructor must have no explicit return type, not even void.
  • 27. • Types of java constructors There are 3 types of constructors: • Default constructor (no-arg constructor) • Parameterized constructor • Copy constructor (object clone)
  • 28. Default constructors class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is "+ vol); } }
  • 29. Parameterized constructor class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; class BoxDemo { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 5); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol);
  • 30. Copy constructor Previous program can be extended with passing object of the class to the constructor itself. Eg: Box (Box b) { System.out.println(“cloning object”); } Public static void main(String args[]) { Box mybox1 = new Box(10, 20, 5); Box mybox2 = new Box(mybox1); //mybox2 is cloned from mybox1 object } } Constructor with different arguments / different number of arguments are called constructor overloading.
  • 31. Java program to illustrate Constructor Overloading class Box { double width, height, depth; // constructor used when no dimensions specified Box() { width = height = depth = 0; } // constructor used when cube is created Box(double len) { width = height = depth = len; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } // Main code public class Test { public static void main(String args[]) { // create boxes using the various constructors Box mybox2 = new Box(); Box mycube = new Box(7); Box mybox1 = new Box(10, 20, 15); double vol; // get volume of first box vol = mybox1.volume(); System.out.println(" Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println(" Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println(" Volume of mycube is " + vol); } }
  • 32. Method Overloading • If a class have multiple methods by same name but different parameters, it is known as Method Overloading. • Method overloading increases the readability of the program. • 2 ways to differentiate the methods which are overloaded 1.by number of arguments 2.by data types
  • 33. 1)Example of Method Overloading by changing the no. of arguments class Calculation { void sum(int a,int b) {System.out.println(a+b);} void sum(int a,int b,int c) {System.out.println(a+b+c);} public static void main(String args[]) { Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } }
  • 34. 2)Example of Method Overloading by changing data type of argument class Calculation2 { void sum(int a,int b) {System.out.println(a+b);} void sum(double a,double b) {System.out.println(a+b); } public static void main(String args[]) { Calculation2 obj=new Calculation2(); obj.sum(10.5,10.5); obj.sum(20,20); } }
  • 35. //Write a program to find area of geometrical figures using method overloading.
  • 36. import java.util.*; class geofig { double area(double r) { return(3.14*r*r); } float area(float s) { return(s*s); } float area(float l,float b) { return(l*b); } double area(double b,double h) { return(0.5*b*h); public static void main(String arg[]) { Scanner sc =new Scanner(System.in); geofig g = new geofig(); System.out.println("enter the value for radius of circle"); double r =sc.nextDouble(); System.out.println("area of circle="+g.area(r)); System.out.println("enter the value for side of a square"); float s =sc.nextFloat(); System.out.println("area of square="+g.area(s)); System.out.println("enter the value for length and breadth of rectangle"); float l =sc.nextFloat(); float b =sc.nextFloat(); System.out.println("area of rectangle="+g.area(l,b)); System.out.println("enter the value for base & height of triangle"); double b1 =sc.nextDouble(); double h =sc.nextDouble(); System.out.println("area of triangle="+g.area(b1,h)); } }
  • 37. Lab 8: import java.util.*; class GarbageCollection { public static void main(String s[]) throws Exception { Runtime rs = Runtime.getRuntime(); System.out.println("Total memory is: " + rs.totalMemory()); System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory()); rs.gc(); System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory()); } }
  • 39.
  • 40. Java Command Line Arguments • The java command-line argument is an argument i.e. passed at the time of running the java program. • The arguments passed from the console can be received in the java program and it can be used as an input.
  • 41. class CommandLineExample{ public static void main(String args[]){ System.out.println("Your first argument is: "+args[0]); } }
  • 43.
  • 44. final keyword • The final keyword in java is used to restrict the user. The java final keyword can be used in many context For example, when a variable is declared with the "final" keyword, its value cannot be changed once it is set: final int a = 10; a = 20; // this will result in a compile-time error
  • 45. the keyword "abstract" is used to declare an abstract class or method. Here's an example of an abstract class: abstract class Shape { abstract double area(); } • An abstract method is a method that is declared in an abstract class, but does not have a body. The purpose of an abstract method is to specify a method signature that must be implemented by any concrete subclasses of the abstract class.
  • 46. • Finalize Keyword in java: • The finalize method in java is called by the garbage collector before an object is garbage collected.