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

OOP1 Unit-4

object oriented program gtu unit 4

Uploaded by

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

OOP1 Unit-4

object oriented program gtu unit 4

Uploaded by

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

Object-Oriented Programming

3140705

Unit 4:
Objects and
Classes
 Looping
What we will learn

Defining classes for objects


Constructors
Accessing objects via reference variable
Using classes from the java library
Static variables, constants and methods
visibility modifiers
Data field encapsulation
Passing objects to methods, array of objects,
Immutable objects and classes,
scope of variable
this reference.

Unit-4
Introduction
Large Data Handling
Class
 Class is derived datatype, it combines members of different datatypes
into one.
 Defines new datatype (primitive ones are not enough).
 For Example : Car, College, Bus etc..
 This new datatype can be used to create objects.
 A class is a template for an object .
Example :
class Car{
String company;
String model;
double price;
double milage;
………
}
Car Class
Class:
Car
Properties (Describe)
Company
Model Methods
Color (Functions)
Mfg. Year Start
Price Drive
Fuel Type Park
Mileage On_break
Gear Type On_lock
Power Steering On_turn
Anti-Lock braking
system
Object
 An object is an instance of a class.
 An object has a state and behavior.
Example: A dog has
states - color, name, breed as well as
behaviors – barking, eating.
 The state of an object is stored in fields (variables), while methods
(functions) display the object's behavior.
What is an Object?
Philosophy of Object Oriented
 Our real world is nothing but classification of objects
 E.g. Human, Vehicle, Library, River, Watch, Fan, etc.
 Real world is organization of different objects which have their own
characteristics, behavior
 Characteristic of Human: Gender, Age, Height, Weight, Complexion,
etc.
 Behavior of Human: Walk, Eat, Work, React, etc.
 Characteristic of Library: Books, Members, etc.
 Behavior of Library: New Member, Issue Book, Return Book etc.
 The OO philosophy suggests that the things manipulated by the program
should correspond to things in the real world.
 Classification is called a Class in OOP
 Real world entity is called an Object in OOP
 Characteristic is called Property in OOP
 Behavior is called Method in OOP
What is an Object?
What is an Object?

Pe Board Lapto
n p

Benc Project Bik


h or e
Physical
objects…
What is an Object? (Cont…)

Result Bank
Account
Logical objects…
What is an Object?
 An Object is a key to
understand Object
Oriented Technology.
 An entity that has state
and behavior is known
as an object. e.g.,
Mobile, Car, Door, OBJECT
Laptop etc
 Each and every object
posses
 Identity
 State
 Behavior
Object: A Real-World Entity
CA
R

Clas
s

Object-1 Object-2 Object-3 Object-4 Object-5


Object: A Real-World Entity

OBJECT:
CAR

Events
Properties
(Describe) On_Start
Manufacturer On_Parked
Model On_Brake
Color
Methods
Year
(Actions)
Price
Start
Drive
Park
Object: A Real-World Entity
Object: A Real-World Entity
Objects of Class Bird
Classes and Objects
Classes and Objects

Cla Obje Obje


ct1 ct2
ss

Class is a blueprint of Object is instance


Classan object the
describes of class
object
What is Class?
 Class can be defined in multiple ways
 A class is the building block.
 A class is a blueprint for an object.
 A class is a user-defined data type.
 A class is a collection of objects of the similar
kind.
 A class is a user-defined data type which
combines data and methods.
 A class describes both the data and behaviors
of objects.
 Class contains data members (also known as field
or property or data) and member functions (also
known as method or action or behavior)
 Classes are similar to structures in C.
 Class name can be given as per the Identifier
What is Object?
 Definition: An Object is an instance of a
Class.
 An Object is a variable of a specific Class
 An Object is a data structure that
encapsulates data and functions in a
single construct.
 Object is a basic run-time entity
 Objects are analogous to the real-world
entities.
Points to Remember
 When a class is defined, only the specification or blueprint for the object is
defined; no memory or storage is allocated.
 When an object of a class is declared, the memory is allocated as per the
data members of a class
 We can access the data members and member functions of a class by
using a . (dot) operator.
 Generally Class contains
 Data Members
 Member Functions
 Constructor (Special Member Function)
Class and Objects
Object 1
Person: P1
Name: Narendra
Modi
Gender: Male
Class Age: 71 Years
Person Person:
Profession:
P1
• Name Politician
• Gender
• Age Object 2
Person:
• Profession
P2
Person: P2
Name: Amitabh
Bachchan
Gender: Male
Age: 79 Years
Profession: Actor
Class and Objects
Object 1
BankAccount: B1
Account_No:
1001123001
BankAccount: balance: 1,00,000
Class B1
BankAccount Object 2
• Account_No BankAccount: B2
BankAccount:
• balance
B2 Account_No:
1001123002
BankAccount: balance: 5,60,0000
B3
Objec
t3
BankAccount: B3
Account_No:
1001123003
balance: 10,000
Class and Objects
Object 1
Cube : C1
Name:C1
Class Cube : C1 Height:20cm

Cube Width:20cm
Object 2
• Name Depth:20cm Cube : C2
• Height Cube : C2 Name: C2
• Width Height:5cm
• Depth
Width:5cm
Cube : C3 Depth:5cm
Objec
t 3 : C3
Cube
Name: C3
Height:10cm
Width:10cm
Depth:10cm
Class and Objects

Person employee of Company


Class Diagram
name * * companyNa
me

John:Perso employee of IBM:Compa


n ny
name companyNa
Parth:Perso me
n
Object Diagram
name
Jaya:Person
name
employee TCS:Compa
Amy:Perso of ny
n companyNa
name me
Class and Objects

Country has CapitalCity


Class Diagram
countryNam 1 1 cityName
e

India:Count has NewDelhi:Capit


ry alCity
countryNam cityName
Canada:Cou
e has Ottawa:CapitalC
ntry ity
countryNam cityName Object Diagram
eFrance:Cou has Paris:CapitalCit
ntry y
countryNam cityName
e
Japan:Coun has Tokyo:CapitalCit
try y
countryNam cityName
e
Creating Object & Accessing members
 new keyword creates new object
 Syntax:
ClassName objName = new ClassName();
Example :
SmartPhone iPhone = new SmartPhone();
 Object variables and methods can be accessed using the dot (.) operator
 Example:
iPhone.storage = 8000;
Declaring an Object
 When we create a class, we are creating a new data type.
 Object of that data type will have all the attributes and abilities that are designed in the
class
MyProg.jav
a
1. class Square{
2. double height;
3. double width; s1 NULL
4. }
5. class MyProg{
6. public static void main(String[]
args) {
7. Square
Square s1=new
s1; Square(); height
s1
8. } width
9. }
 The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it.
 This reference is, more or less, the address in memory of the object allocated by new.
 This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Declaring an Object
MyProg.jav
a
1. class Square{
2. double height; An object reference is
3. double width; similar to a memory
4. } pointer.
5. class MyProg{
reference
6. public static void main(String[] args) { s1 NULL
7. Square s1; //declare reference to object
8. s1= new Square();//allocate a Square object
9. }
10.} Allocates
Memory height
 new operator dynamically allocates memory fors1an
at object
Runtime
width
 Here, s1 is a variable of the class type.
 The class name followed by parentheses specifies the constructor for the
class.
 It is important to understand that new allocates memory for an object
during run time.
Assigning Object Reference
ObjectDemo.java ObjectDemo.java

Rectangle r1=new Rectangle r1=new


Rectangle(); Rectangle();
Rectangle r2=r1; Rectangle r2=r1;
r1 …
R1=null
Width r1
Height
Width
r2 Height

Here, r1 and r2 will both refer to the same object. r2


The assignment of r1 to r2 did not allocate any
memory or copy any part of the original object. It
simply makes r2 refer to the same object as does Here, r1 has been set to null, but r2 still
r1. points to the original object.
WAP using class Person to display name and
age
1. class MyProgram { 15.class Person
2. public static void main(String[] args) 16.{
{ 17. String name;
3. Person p1= new Person();
4. Person p2= new Person(); 18. int age;
5. p1.name="modi"; 19.}//class person
6. p1.age=71;
7. p2.name="bachchan";
8. p2.age=80;
9. Outp
ut
System.out.println("p1.name="+p1.name); p1.name=modi
p2.name=bachcha
10. n
System.out.println("p2.name="+p2.name); p1.age=71
p2.age=80
11.
WAP using class Person to display name and age with method

1. class MyProgram { 15.class Person{


2. public static void 16. String name;
17. int age;
main(String[] args){ 18.public void displayName(){
19.
3. Person p1=new System.out.println("name="+name)
Person(); ;
4. Person p2=new 20. }
Person(); 21.public void displayAge(){
5. p1.name="modi";
Outp
6. p1.age=71; 22. ut
7. p2.name="bachchan"; System.out.println("age="+age);
name=modi
name=bachchan
8. p2.age=80; 23. } age=71
9. p1.displayName(); 24.}//class person age=80
WAP using class Rectangle and calculate area using method

1. import java.util.*; 13.class Rectangle{


2. class MyProgram { 14.float height;
3. public static void main(String[] 15.float width;
args){ 16.public void
4. Rectangle r1=new Rectangle(); calArea() {
17.System.out.println(
5. Scanner sc=new Scanner(System.in); "Area="+height*width
);
6. System.out.print("enter height:"); 18. } //calArea()
19.} //class
Outp
7. r1.height=sc.nextFloat(); ut
8. System.out.print("enter width:"); enter height:30.55
enter width:20.44
9. r1.width=sc.nextFloat(); Area=624.442
10. r1.calArea();
11. } //main()
WAP using class Rectangle and calculate area with Return value

1. import java.util.*; 15.class Rectangle{


2. class MyProgram { 16.float height;
3. public static void main(String[] 17.float width;
args){ 18.public float
4. float area; calArea() {
5. Rectangle r1=new Rectangle(); 19. return
height*width;
6. Scanner sc=new Scanner(System.in); 20. }//calArea()
21.}//class
7. System.out.print("enter height:");
Outp
ut
8. r1.height=sc.nextFloat(); enter height:30.55
9. System.out.print("enter width:"); enter width:20.44
Area=624.442
10. r1.width=sc.nextFloat();
11. area=r1.calArea();
WAP using class Cube and calculate area using method with parameter

1. import java.util.*; 11.class Cube{


2. class MyProgramCube { 12.float height;
3. public static void main 13.float width;
4. (String[] args) 14.float depth;
{ 15.float calArea(float h,
5. float area; float
6. Cube c1= new Cube(); w, float d)
7. area=c1.calArea(10,10,10); 16.{ height=h;
17. width=w;
8. System.out.println("area="+are 18. depth=d;
a); 19. return
9. }//main() height*width*depth;
10.}//class myProgram 10 10
20. }//calArea()
Outp
ut 10 21.}//class
area=1000.0
WAP using class Cube and calculate area of two objects

1. import java.util.*; 12.class Cube{


2. class MyProgramCube { 13.float height;
3. public static void main 14.float width;
4. (String[] args) 15.float depth;
{ 16.float calArea(float h,
5. float area; float
6. Cube c1= new Cube(); //Obj1 w, float d)
7. Cube c2= new Cube(); //Obj2 17.{ height=h;
8. System.out.println(“c1 area=“ 18. width=w;
19. depth=d;
+c1.calArea(10,10,10)); 20. return
9. System.out.println(“c2 area=“ height*width*depth;
20
20
21. } //calArea()Outp
ut
+c2.calArea(20,20,20)); 10 10 22.} //class c1 area=1000.0
20
10. } //main() 10 c2 area=8000.0
11.} //class
class Box {
double length;
length = 10
length
double breadth;
double height; myBox1
} breadth = 20
breadth
class BoxDemo {
public static void main(String args[]) { height = 30
height
Box myBox1 = new Box();
Box myBox2 = new Box();
double vol;
length
length =3
myBox1.length = 10;
myBox1.breadth = 20; myBox2 breadth
breadth
=6
myBox1.height = 30;
height
height
=9
myBox2.length = 3;
myBox2.breadth = 6;
myBox2.height = 9;

vol = myBox1.length * myBox1.breadth *


myBox1.height;
System.out.println("Volume is " + vol);
vol = myBox2.length * myBox2.breadth *
myBox2.height;
System.out.println("Volume is " + vol);
}
Class vs. Object
Class Object
Class is a Blueprint or template. Object is the instance of a class.
Class creates a logical framework When you declare an object of a
that defines the relationship class, you are creating an instance
between its members. of that class.
Class is a logical construct. An object has physical reality. (i.e.,
an object occupies space in
memory.)
Class is a group or collection of An Object is defined as real-world
similar object. entity
e.g. Car e.g.:Audi, Volkswagen, Tesla, Ferrari
Class is declared only once An Object can be created as many
etc.
times as required
Class doesn’t allocate memory An Object allocates the memory
when it is created. upon creation
Class can exist without its objects. An Object can’t exist without a
Class: Profession class.
Object: Doctor, Teacher, Lawyer,
Class: Mobile Politician…
Class: Subject Object: iPhone, Samsumg, 1plus…
Class: Student Object: Maths, English, Science,
Class: Color Computer…
Object: John, Aarav, Smita…
Constructor
Constructor
 A constructor in Java is a special type of 1. class Cube{
method that is used to initialize objects. 2. instance variable1
 The constructor is called when an object of a 3. instance variable1
class is created. 4. …
A constructor initializes an object 5. Cube()
immediately upon creation. 6. {
 It has the same name as the class in which it 7. //initailze
resides and is syntactically similar to a
method. object }
 JVM first allocates the memory for variables 8. } //class
(objects) and then executes the constructor to
initialize instance variables.
 The JVM calls it automatically when we create
an object.
 A constructor defines what happens when an
Properties of constructor
 Constructor is invoked automatically whenever 1. class Demo{
an object of class is created. 2. instance variable1
 Constructors do not have return types and they 3. instance variable1
cannot return values, not even void. 4. …
 All classes have constructors by default: if you 5. Demo()
do not create a class constructor yourself, Java 6. {
creates one for you known as default 7. //initailze
constructor.
 Constructor is a method that is called at runtime object }
during the object creation by using the new 8. } //class
operator. The JVM calls it automatically when we
create an object.
 It is called and executed only once per object.
 It means that when an object of a class is
created, constructor is called. When we create
2nd object then the constructor is again called
Types of Constructor

Construct
or

No- Parameteriz Copy


Default
Argument ed Constructor
Default Constructor
Default Constructor: MyConst.java
1. class MyConst {
2. public static void main(String[]
args) {
3. MyConst c=new
MyConst();
e r
4. } l
pi After
5. }
C om Compilation
1. class MyConst{
2. MyConst(){
3. //Default Constructor…
4. }
5. public static void main(String[]
args) {
6. c=new MyConst();
7. }
8. }
Default Constructor
 Once you define your own constructor, the default constructor is no longer
used.
 The default constructor automatically initializes all instance variables to
zero.
1. class MyAccount{ 8. class MyBank {
Example:
2. int accNo; 9. public static void main(String[] args){
3. double balance; 10. MyAccount ma= new MyAccount();
4. MyAccount(){ 11.
5. //default constructor System.out.println("balance="+ma.balance);
12. }//main()
6. }
7. }//class 13.}//class

Outp
ut
balance=0.0
No-Argument
Constructor
No-Argument Constructor: MyMain.java
1. class Cube { 13.class MyMain{
2. double width; 14.public static void
main(String[] args){
3. double height;
15. Cube c=new Cube(
4. double depth;
5. Cube()
16. }
6. {
17.}
7. System.out.println("
If you implement any constructor then you no
Constructing cube"); longer receive a default constructor from Java
compiler.
8. width = 10;
9. height = 10;
10. depth = 10;
11. }//Cube()
12.}//class
Parameterized
Constructor
Parameterized Constructor: MyMain.java
1. class Cube { 10.class MyMain{
2. double width, height, depth; 11.public static void
main(String[] arg
3. Cube(double w, double h, double
{
d)
12. Cube c=new
4. { System.out.println("
Cube(10,10,10);
Constructing cube"); 13. }
5. width = w; 14.}
6. height = h;
7. depth = d;
8. }//Cube()
9. }//class
Parameterized Constructor: MyMain.java with
method
1. class Cube { 13.class MyMain{
2. double width,height,depth; 14.public static void
main(String[] args){
3. Cube(double w, double h, double d)
4. { System.out.println("Constructing 15. Cube c=new Cube(10,10,10);
cube");
16. c.calVolume();
5. width = w;
17. }
6. height = h;
18.}
7. depth = d;
8. }//cube()
9. void calVolume(){
10. System.out.println("Volume="

+width*height*depth);
11. } //calVolume()
12.} //class
Parameterized Constructor: method with return
value
1. class Cube { 13.class MyMain{
2. double width,height,depth; 14.public static void
main(String[] args){
3. Cube(double w, double h, double d)
15. double vol;
4. { System.out.println("Constructing
cube"); 16.Cube c=new Cube(10,10,10);
5. width = w; 17. vol=c.calVolume();
6. height = h; 18. System.out.println("
7. depth = d; Volume="+vol);
8. }//cube() 19. }
9. double calVolume(){ 20.}
Outp
10. return width*height*depth; ut
11. }//calVolume() Constructing
12.}//class cube
Volume=1000.0
this

‘this’ keyword
class Box {
double length;
double breadth;
double height;
Box(doublel,
Box(double length,
doubledouble breadth,
b, double h) { double
height) {
System.out.println("Constructing Box");
this.length
length
length =
= l; = length;
length; Creates
length ambiguity
is instance for
variable
this.breadth = breadth;
breadth = breadth; compiler
as well as length is formal
breadth = b;
this.height = height;
height = height;
height = h; parameter of method
}
void volume() {
double volume = length * breadth * height;
System.out.println("Volume is " + volume);
}
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box(10,20,30);
Box myBox2 = new Box(3,6,9);
myBox1.volume();
myBox2.volume();
}
‘this’ Keyword
 this is a reference variable that refers to the
current object.
 this can be used to invoke current object's
method. This
 this() can be used to invoke current class
constructor
 this can be passed as a parameter to
constructor and method call.
 this can be used to return the current object
from the method.
Copy Constructor
Copy Constructor
 It is a special type of constructor that
is used to create a new object using Constructor 2(Constructor
Constructor 1()
1)
the existing object of a class that had {
{
been created previously. …

}
 It creates a new object by initializing }
the object with the instance of the Copy Constructor
same class.
Copy Constructor: MyProgramCopy.java
1. class Student{ 19. class MyProgramCopy {
2. String name; 20. public static void main(String[]
3. int rollno; args){
4. Student(String s_name, int s_roll){ 21. float area;
5. 22. Student s1=new
System.out.println("ConstructorInvoked"); Student("darshan",101);
6. this.name=s_name; 23. //invoking Copy Constructor
7. this.rollno=s_roll; 24. Student s2=new Student(s1);
8. } //Constructor1 25. s1.display();
26. s2.display();
9. Student(Student s){ 27. } //main()
//CopyConstructor 28. } //class myProgram
10. System.out.println("CopyConstructor
Outp
ut
Invoked"); Constructor Invoked
11. this.name=s.name; CopyConstructor Invoked
12. this.rollno=s.rollno; name=darshan
13. } //Constructor2 rollno=101
name=darshan
14. public void display(){ rollno=101
15. System.out.print("name="+name);
16. System.out.println("
Advantages of Copy Constructor
 It is easier to use when our class contains a
complex object with various parameters. Constructor 2(Constructor
Constructor 1()
1)
 Whenever we need to add all the field of a {
{

class to another object, then just send the …
}
reference of previously created object. }

 One of the most importance of copy Copy Constructor


constructors is that there is no need for any
typecasting.
 Using a copy constructor, we can have
complete control over object creation.
 With Copy Constructor, we can pass object
of the class as a parameter(pass by
reference).
Constructor
Overloading
Constructor Overloading
 In addition to overloading normal methods, you can also overload
constructor methods. 1. class Account{
1. class Balance{ 2. public static void
2. int accNo; main(String
3. double bal; args[]){
4. Balance(){ 3. Balance b1= new Balance();
5. System.out.println("inside
4. Balance b2= new Balance(100);
const1"); 5. Balance b3=new
6. bal=0; Balance(1201,10000);
7. } 6. System.out.println("b1.bal="+b1.b
8. Balance(double b){ al);
9. System.out.println("inside
7. System.out.println("b2.bal="+b2.b
const2"); al);
10. bal=b; 8. System.out.println("b3.bal="+b3.b
11. } al+
12. Balance(int a,double b){ "b3.accNo="+b3.accNo);
13. System.out.println("inside
9. }
const3"); 10.}sssssssss
14. bal=b;
Why Constructor?
 The pivotal purpose of constructor is to initialize the instance
variable of the class.
 We use constructors to initialize the object with the default or initial
state.
 Through constructor, we can request the user of that class for
required dependencies.
 A constructor within a class allows constructing the object of the
class at runtime.
 Allocates appropriate memory to objects.
 If we need to execute some code at the time of object creation, we
can write them inside the constructor.
 Example:
 If we talk about a Cube class then class variables are width,
height and depth.
 But when it comes to creating its object(i.e Cube will now exist in
When to use Constructor?
 When we need to execute some code at the time of object creation.
 Used for the initialization of instance variables.
 To assign the default value to instance variables.
 To initializing objects of the class.
Constructor() vs. Method()
Constructor() Method()
Naming Constructor name must be same as Method name can be anything.
class name.
Return types Constructor does not have any return Method must have return types, at
type, not even void. least void.
Call Constructor can be invoked implicitly Method is called by the programmer.
when object is created. Invoked explicitly.
Purpose To initialize an object To execute the code
Inheritance Constructor cannot be inherited by Method can be inherited by subclass.
subclass.
Destructor
Destructor
 Destructor is the opposite to the constructor. Constructor is
used to initialize objects while the destructor is used to delete
or destroy the object that releases the resource occupied by the
object.
 Definition: Destructor is an instance member function which is
invoked automatically whenever an object is going to be
destroyed.
 In other words, a destructor is the last function that is going to
be called before an object is destroyed.
 In java, there is a special method named garbage collector
that automatically called when an object is no longer used.
 When an object completes its life-cycle the garbage collector
deletes that object and de-allocates or releases the memory
occupied by the object.
 In C++, dynamically allocated objects must be manually
released by use of a delete operator.
Destructor
Why Destructor?
 When we create an object of the class(using new), it occupies some
space in the memory. If we do not delete these objects, it remains in
the memory and occupies unnecessary space.
 To resolve this problem, we use the destructor.
 Remember that there is no concept of destructor in
Java.
 Instead of destructor, Java provides the garbage collector
that works the same as the destructor.
 The garbage collector is a program (thread) that runs on
the JVM. It automatically deletes the unused objects (objects
that are no longer used) and free-up the memory.
 The programmer has no need to manage memory,
manually.
Working of garbage collector(destructor) in java
 When the object is created it occupies the space in
the heap. These objects are used by the threads.
 If the objects are no longer used by the thread it
becomes eligible for the garbage collection.
 The memory occupied by that object is now available
for new objects that are being created.
 When the garbage collector destroys an object, the
JRE calls finalize() method to close the connections
such as database and network connection.
Static
Static in java

Static in Java

Static Variable Static Method Static Block Static Class


Static
 The static keyword is used for memory management.
 We can apply static keyword with variables, methods, blocks and nested
classes.
 The static keyword belongs to the class than an instance of the class.
 The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Static Variable
 Static variables have a property of preserving their value even after they
are out of their scope.
 The static variable gets memory only once in the class area at the time of
class loading.
 Advantage of static variable: It makes program memory
efficient (static variable saves memory).
 Characteristics of static variable:
 It is initialized to zero when the first object of its class is created. No
other initialization is allowed.
 Only one copy of that member is created for the entire class and is
shared by all the objects of that class, no matter how many objects are
created.
 It is visible only within the class, but its lifetime is the entire program.
 Static variables are normally used to maintain values common for all
objects.
 The class constructor does not initialize static variable.
Static vs Non-Static Function
MyProgram.java(Non-static MyProgram.java(static
function) function)
1. public class MyProgram { 1. public class MyProgram {

2. public static void 2. public static void


main(String[] args) { main(String[] args) {

3. int a=1,b=2,c; 3. int a=1,b=2,c;


4. MyProgram mp=new 4. c = add(a,b);
5. System.out.println(c);
MyProgram(); 6. }//main
5. c = mp.add(a,b);
6.
System.out.println(c); }// 7. static int add(int i,int
main j)
7. public int add(int i,int 8. { return i +
j) j;
8. { 9. }
9. return i + j; 10.}//class
10. }
11.}//class
Characteristic of static method
 A static method can call only other static methods and can not call a non-
static method from it.
 A static method can be accessed directly by the class name and doesn’t
need any object
 A static method cannot refer to “this” or “super” keywords in anyway
Static Method: WAP using class Rectangle and calculate area

1. import java.util.*; 13.class MyRectangle {


2. class Rectangle{ 14.public static void main(String[] args)
3. static float height; {
4. static float width; 15. Rectangle r1= new Rectangle();
5. static void calArea() {
16. Scanner sc= new Scanner(System.in);
6. System.out.println( "Area= "
17. System.out.print("enter height:");
+height*width);
Outp
7. ut
} //calArea() 18. r1.height=sc.nextFloat();
enter height:30.55
8. } //class
enter width:20.44 19. System.out.print("enter width:");
Area=624.442
20. r1.width=sc.nextFloat();
static keyword
 static keyword is mainly used for memory management.
 It can be used with
 Variables
 Methods
 Blocks
 Nested classes
 Basically, static is used for a constant variable or a method that is same
for every instance of a class.
 The static variable can be used to refer to the common property of all
objects.
 The static variable gets memory only once in the class area at the time of
class loading.
 It makes your program memory efficient.
 Syntax
class Student {
int rollNo;
String name;
static
String String
collegecollege = "DIET";
= "DIET";
.
.
.
}
class StudentDemo {
public static void main(String
args[]) {
Student student1 = new
Student();
Student student2 = new
Student(); student1 student2 student3
Student student3 = new
rollNo
Student();
.
name
.
.
college DIET DIET DIET
}
}
college DIET
static method
 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance
of a class.
 A static method can access static data member and can change the value
of it.
 Restrictions
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
class Student {
int rollno;
String name;
static String college="abc";
static void change() {
college = "DIET"; We can not use non-static
rollno = 10; variables in static
} methods
Student(int r, String n) {
rollno = r;
name = n;
}
void display() {
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStaticMethod {
public static void main(String args[]) {
Student.change();
Student s1 = new Student(111,"Tom");
Student s2 = new Student(222,"Jerry");
s1.display();
s2.display();
}
}
Static Block
 Static block is executed exactly once, when the class is first loaded.
 It is used to initialize static variables of the class.
 It will be executed even before the main() method.
 Syntax static {
//initialisation of static
variables…
}
 How to call static block in java?
 Unlike method, there is no specified way to call a static block.
 The static block executes automatically when the class is loaded in
memory.
Example: Static Block, Method and Variable
1. class StaticDemo {
2. static int a = 4; //static variable declared & initialized
3. static int b; //static variable declared
4. static void dispValue(int x) { 3
5. System.out.println("Static method initialized.");
6. System.out.println("x = " + x);
7. System.out.println("a = " + a);
8. System.out.println("b = " + b);
9. } //static method
10. static {
11. System.out.println("Static block initialized.");
Outp
12. b= a * 5; ut
1
13. } //static block Static block
14. public static void main(String args[]) { initialized.
2
15. System.out.println("inside main()..."); inside main()...
16. dispValue(44); Static method
17. } //main() initialized.
18.} //class x = 44
a = 4
Points to remember for static keyword
1. When we declare a field static, exactly a single copy of that field is
created and shared among all instances of that class.
2. Static variables belong to a class, we can access them directly using
class name. Thus, we don't need any object reference.
3. We can only declare static variables at the class level.
4. We can access static fields without object initialization.
5. Static methods can't be overridden.
6. Abstract methods can't be static.
7. Static methods can't use this or super keywords.
8. Static methods can't access instance variables and instance methods
directly. They need some object reference to do so.
9. A class can have multiple static blocks.
Mutable and Immutable Objects
 The content of mutable object can be changed, while content of
immutable objects can not be changed.
class MutableClass{ class ImmutableClass{
int a; int a;
void add5() { int add5() {
a = a + 5; return ( a + 5 );
} }
} }
public class MutableClassDemo { public class MutableClassDemo {
public static void main(String[] public static void main(String[] args) {
args) { ImmutableClass m1 = new
MutableClass m1 = new ImmutableClass();
MutableClass(); m1.a = 10;
m1.a = 10; int ans = m1.add5();
m1.add5(); System.out.println("A in m1 = " +
System.out.println(m1.a); m1.a);
} System.out.println("returned = " +
} ans);
}
}
Passing Objects as Argument
 In class Time{
order to int hour;
understand int minute;
how and why int second;
public Time(int hour, int minute, int
we need to second) {
pass object as this.second = second;
an argument in this.minute = minute;
this.hour = hour;
methods, lets } public class TimeDemo {
see the below void add(Time t) { public static void main(String[]
this.second += t.second; args) {
example. if(this.second>=60) { Time t1 = new Time(11,59,55);
this.minute++; Time t2 = new Time(0,0,5);
this.second-=60;
} t1.add(t2);
this.minute += t.minute;
if(this.minute>=60) { System.out.println(t1.hour + ":"
this.hour++; + t1.minute + ":" + t1.second);
this.minute-=60; }
} }
this.hour += t.hour;
}
}
Array of Objects
 We can create an array of object in java.
 Similar to primitive data type array we can also create and use arrays of
derived data types (class).
class Student{ public class ArrayOfObjectDemo {
int rollNo; public static void main(String[] args)
String name; {
Student[] stu = new Student[3];
public Student(int rollNo, String
name) { stu[0] = new
this.rollNo = rollNo; Student(101,"darshan");
this.name = name; stu[1] = new Student(102, "OOP");
} stu[2] = new Student(103,"java");

void printStudentDetail() { stu[0].printStudentDetail();


System.out.println("| "+ stu[1].printStudentDetail();
rollNo stu[2].printStudentDetail();
+" | -- | "+ }
name +" |"); }
}
}
Nested Class
Nested Class
 Nested Class: Class within another class
 Scope: Nested class is bounded by the scope of its
enclosing class.
 E.g. class B is defined within class A, then B is known to
A, but not outside of A. A: Outer Class

 A nested class has access to the members,


including private members of the class in which it B: Nested
is nested. Class

 However, the enclosing class does not have access


to the members of the nested class. i.e. Class B
can access private member of class A, while
reverse is not accessible.
Nested Class
Nested Class
 Types of Nested class:

Nested Class

Static Non- Static


Nested Class Nested Class
Non-Static Nested Class: InnerOuterDemo.java
1. class Outer{
2. private int a=100;//instance variable 16. class InnerOuterDemo{
3. void outerMeth(){ 17. public static void
4. Inner i= new Inner(); main(String[]
args)
5. System.out.println("inside outerMeth()...");
18. {
6. i.innerMeth();
19. Outer o= new
7. } Outer();
8. class Inner{ 20. o.outerMeth();
9. int b=20; 21. }
10. void innerMeth(){ 22. } //InnerOuterDemo
11. System.out.println("inside innerMeth()..."
12. +(a+b));
13. }
14. } //inner class
15. } //outer class Outp
ut
inside outerMeth()...
inside
innerMeth()...120
Static Nested Class: InnerOuterDemo
1. class Outer{ error: non-static variable a
2. static cannot be referenced from a
int a=100; 16. class InnerOuterDemo{
int a=100;//instance variable
3. static context
void outerMeth(){ 17. public static void
4. Inner i= new Inner(); main(String[]
args)
5. System.out.println("inside outerMeth()...");
18. {
6. i.innerMeth();
19. Outer o= new
7. } Outer();
8. static class Inner{ 20. o.outerMeth();
9. int b=20; 21. }
10. void innerMeth(){ 22. } //InnerOuterDemo
11. System.out.println("inside innerMeth()..."
12. +(a+b));
13. }
14. } //inner class
15. } //outer class Outp
ut
inside outerMeth()...
inside
innerMeth()...120
Points to remember: Inner class
 Inner class implements a security
mechanism in Java.
 Reduces encapsulation, more
organized code by logically grouping
A: Outer Class
the classes.

B: Nested
Class
Package (Not part of this Unit)
 A Package can be defined as a grouping of related types providing
access protection and name space management.
 Programmers can define their own packages to bundle group of
classes/interfaces, etc.
 Packages are used in Java in order to
1. prevent naming conflicts
2. control access,
3. make searching/locating of classes/interfaces easier.
 It is a good practice to group related classes implemented so that a
programmer can easily determine that the classes, interfaces are related.
Creating a package
 To create a package you need to write package statement followed by
the name of the package.
 Syntax : package package_name;
 Example : package darshan_student;

class Student {
// code
}

 The package statement should be the first line in the source file.
 There can be only one package statement in each source file, and it
applies to all types in the file.
 If a package statement is not used then the class/interfaces will be put
into an unnamed package.
Package (Example)
package myPackage;
public class Animal {
public String name;
public void eat(){
System.out.println("Organic Food !!!!");
}
public static void main(String[] args){
Animal a = new Animal();
a.eat();
}
}
.
Represent the current
 To compile directory
javac –d . Animal.java
 To Run the class file
java myPackage.Animal
import keyword
 import keyword is used to import built-in and user-defined packages into
your java source file so that your class can refer to a class that is in
another package by directly using its name.
 There are 3 different ways to refer to class/interface that is present in
different package
 import the class/interface you want to use.
 import all the classes/interfaces from the package.
 Using fully qualified name.
 We can import
importajava.util.Scanner;
class/interface of other package using a import keyword
at the firstpublic
line ofclass
code.DemoImport {
 Example : public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// Code
}
}
import (importing all class/interface)
 We can import all the classes/interfaces of other package using a import
keyword at the first line of code with the wildcard (*).
 Example :import java.util.*;
public class DemoImport {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Date d = new Date();
// Code
}
}
 It is possible to use classes from other packages without importing the
class using fully qualified name of the class.
 Example :java.util.Scanner s = new java.util.Scanner(System.in);
Static Import
 The static import feature of Java 5 facilitate the java programmer to
access any static member of a class directly.
 Advantage : Less coding is required if you have to access any static
member of a class more frequently.
 Disadvantage : If you overuse the static import feature, it makes the
program unreadable and unmaintainable.

import static java.lang.System.out;


public class S2{
public static void main(String args[]){
out.println("Hello main");
}
} We need not to write
System.out as we have
imported the out
statically
Access Control

Modifier Same Same Same Differe Differe


Class Packag Packag nt nt
e e Packag Packag
Sub Non e e
Class Sub Sub Non
Class Class Sub
Class
Private
Default
Protecte
d
Programs
 Write a class named Rectangle to represent a rectangle. It contains
following members:
Data: width (double) and height (double) that specify the width and height
of the rectangle.
Methods:
1. A no-arg constructor that creates a default rectangle.
2. A constructor that creates a rectangle with the specified width and
height.
3. A method named getArea() that returns the area of this rectangle.
4. A method named getPerimeter() that returns the perimeter.
 Write a program to create circle class with area function to find area of
circle.
 Define time class with hour and minute. Also define addition method to
add two time objects.
 Declare a class called student having following data members:id_no,
no_of_subjects_registered, subject_code, subject_credits,
grade_obtained and spi. Define constructor and calculate_spi
Thank You

You might also like