You are on page 1of 40

Object Oriented

Programming
Mrs. Apurwa Barve
static keyword (IMCC)

class

static
method variables
keyword

imports

 Following are the limitations of static members :


1. They can only call other static methods.
2. They can only read other static variables.
3. They can not refer to ‘this’ or ‘super’

 Any member can de made static by using the keyword, ‘static’ in its declaration.
Mrs. Apurwa Barve
static keyword - variables (IMCC)

 By rule all the instance variables are copied in every object. Hence as many objects of a
class we create, those many copies of instance variables are created. Each copy will
hold its own values within it. Let’s say we have a class Square with instance variables,
side, area, volume. As many objects I create of Square class, all those objects will have
their OWN values of side, area and volume because instance variables will be copied
separately for them.
 When you need to share common values between different objects of your class you
make that value STATIC.
 static is a keyword in Java which is a non-access modifier. Syntax is:
accessmodifier static variableName[=initialization value];
 When a variable is declared static, its copy is NOT made for every variable. Only one
copy is created in the class and referred by all objects(instances).
 static variable(s) can be initialized in ini
 They can be accessed only from within other static methods.
 To access static variables you DO NOT need an object of the class. Just the class name is
enough to access these static members. They are also called as CLASS MEMBERS.
Mrs. Apurwa Barve
Class activity - 6 (IMCC)

You already have a Pizza class which you use to bake pizzas as per customer specification.
Let’s say you decide to count the total number of pizzas you bake in a day. For this you will
need a counter which should get incremented by 1 each time any object of Pizza class bakes
a pizza.
Also, you will need an additional method, showPizzaCount() which will return the total
number of baked pizzas.
Thus, total number of baked pizzas is a COMMON value between different objects of Pizza
class. Hence we will need to have that as a STATIC variable.
Implement the following changes in your Pizza class :
a. Add following variable and initialize it to 0.
public static int totalPizzaBaked=0;
b. Increment this variable by 1 in bakePizza() method.
c. Add a method showPizzaCount() which will return totalPizzaBaked variable.

Watch static variable video to understand static variable and above implementation.
Mrs. Apurwa Barve
static variables (IMCC)

To understand more about static variables watch,


StaticVariable video
Mrs. Apurwa Barve
Class activity - 7 (IMCC)

Write a class CupCakes with following details:


a. It should have instance variables, flavor and price.
b. It should have static variable totalCupCakes. Initialize this value to some number passed
as an argument to the constructor. This value represents the total number of cup cakes
available for sale.
c. It should have a method, saleCupCake(int nbr) where nbr is the number of cupcakes you
are selling. With each call to this method, deduct the nbr from totalCupCakes.
d. It should have a method, cupCakesLeft() which should return the current value of
totalCupCakes.
Mrs. Apurwa Barve
static keyword - method (IMCC)

 Declaring a method static allows it to be accessed using class name only. We do not
have to create an object of that class to access/invoke that method.
 Syntax to access static method :
className.methodName();
 main() is a famous static method.
public static void main(String args[])
 static method belongs to the class instead of the object.
 It can access static data member and change its value.
 Modify Pizza class and make showPizzaCount() static. It will now look like,
public static int showPizzaCount()
{
System.out.println(Pizza.totalBakedPizza);
}
We can call showPizzaCount() as follows:
Pizza.showPizzaCount();
Mrs. Apurwa Barve
static keyword - class (IMCC)

 Covered within inner class section of notes.


Mrs. Apurwa Barve
static import (IMCC)

Consider,
Importing a class using ‘static’ keyword
package samples;

import static java.lang.Math.*;


//this class demonstrates the use of static keyword with import statements
class StaticImports
{
public void useMathsMethod()
{
//we will be using few methods of Math class without using the class name
System.out.println("Calling Math.pow()");
System.out.println(pow(2,2)); Using Math class
System.out.println("Calling max()"); methods without
System.out.println(max(4.5,3.2)); appending class name
}
}
public class StaticImportsDemo {
public static void main(String args[])
{
StaticImports stimpobj=new StaticImports();
stimpobj.useMathsMethod();
}
}
Mrs. Apurwa Barve
Inner/Nested Classes (IMCC)
Mrs. Apurwa Barve
Inner Classes (IMCC)

Member Inner class :

 Class that is declared within a class but outside a method.

 Can be accessed either from within the class or outside the class.
Mrs. Apurwa Barve
Inner Classes (IMCC)

Consider the following code snippet


class OuterClass
{
private int var=10;

//this is an Inner class


class InnerClass
{ Can access private
public void m1() member of outer class
{

System.out.println("The value of var is...."+var);


}
}

//to access the inner class from within the outer class
public void accessMethod()
{
InnerClass inObj = new InnerClass();
inObj.m1(); Instantiating inner class
} object to access its members
from WITHIN the outer class
}
Mrs. Apurwa Barve
Inner Classes (IMCC)

public class InnerClassDemo {


public static void main(String args[]){ Accessing inner class
OuterClass outObj=new OuterClass(); members using outer class
method.
outObj.accessMethod();

//to access inner class from outside the outer class


OuterClass.InnerClass inObjOut= outObj.new InnerClass();

inObjOut.m1();
} Instantiating Inner class
} object to access its
Directly accessing inner member from OUTSIDE
class member using its the outer class
instance.

The output of the above code is

The value of var is....10


The value of var is....10
Mrs. Apurwa Barve
Inner Classes (IMCC)

Anonymous Inner class :

 Class that is declared within a class but have no name.

 The name of such class is decided by the compiler.

 Enable us to declare and instantiate the class at the same time.

 Should be used instead of a local inner class when you need to use such a class only
once.

 They can be created either by class or by interface.


Mrs. Apurwa Barve
Inner Classes – Anonymous inner class (IMCC)

Consider the code snippet below :


Declaring an abstract class
abstract class AbsAnonymous
{
public abstract void m1();
} Declaring and instantiating an
anonymous inner class having
implementation of the abstract class.
public class AnonymousClassDemo {

public static void main(String args[])


{
AbsAnonymous anonymounsObj = new AbsAnonymous() {

public void m1() {

System.out.println("This is an anonymous inner class implementation");


}
}; Declaration ends with ;
anonymounsObj.m1();
}
} Object of anonymous inner
class which implemented
abstract class.
Mrs. Apurwa Barve
Inner Classes – Anonymous inner class (IMCC)

The output of the above code is

This is an anonymous inner class implementation


Mrs. Apurwa Barve
Inner Classes – Local inner class (IMCC)

Local Inner class :


 It is defined within a block of code generally a method.

 To invoke the members of this class you have to instantiate it within the method.

 These cannot be private, public or protected.

 They can not access non- final local variables.


Mrs. Apurwa Barve
Inner Classes – Local inner class (IMCC)

Consider this code snippet

class LocalInnerClass
{
private int var=10; Defining local inner class
public void m1()
{

class LocalInner
{
public void readVar()
{
System.out.println("the value of var is..."+var);
}
} Instantiating the local class
LocalInner locObj = new LocalInner();
locObj.readVar();
}
Calling local class method
}
using its object
Mrs. Apurwa Barve
Inner Classes – Local inner class (IMCC)

public class LocalInnerClassDemo


{
public static void main(String args[])
{
LocalInnerClass locInnObj = new LocalInnerClass(); Access the local inner class using the
object of the outer class and calling
locInnObj.m1(); the method of the outer class that
} has the local inner class.
}

The output of the above code is

the value of var is...10


Mrs. Apurwa Barve
Inner Classes – Static nested class (IMCC)

Static Nested class :


 Declared within a class and are static

Can not access non static members of the outer class.

 Can access static data members of the outer class, including private members.

 ‘static’ keyword does not do to the class that it does to the other members for
which it is used i.e we need to create an object of the static inner class to access its
members.
Mrs. Apurwa Barve
Inner Classes – Static nested class (IMCC)

Consider this code snippet Declaring the static nested class.


class StaticNestedClass
{
static private int var=30;
static class StClass Can access only static members
{
public void m1()
{
System.out.println("the value of var is.."+var);
} Object of static nested class
} is created by referring to the
} Outer class
public class StaticNestedDemo {
public static void main(String args[])
{
StaticNestedClass.StClass stObj =new StaticNestedClass.StClass();

stObj.m1();
}
} Calling the static class’s
method
Mrs. Apurwa Barve
this keyword (IMCC)

this

To overcome
To refer to
instance
CURRENT object
variable hiding
Mrs. Apurwa Barve
this keyword (IMCC)

To overcome instance variable hiding


 When the instance variables and the local variables have same name we can
get into naming conflict and end up up using the wrong variable.
 To prevent this we can use the ‘this’ keyword and initialize and use the instance
variable. While the local variable can be used without adding ‘this’ keyword to
it.
 Instance variable hiding is also known as name shadowing.
Mrs. Apurwa Barve
this keyword (IMCC)

class Dog
{ //in the above print statements we access the
String breed; //properties of the current Dog
int age; //class object by using the keyword ,'this'
String colour; //followed by (.) and the variable name.
}
//Below we have a parametrised constructor which }
//takes 3 arguments. public class ThisDemo1 {
Dog(String breed,int age,String colour) public static void main(String args[])
{ {
//using this keyword we will avoid instance //we will instantiate the class Dog by passing
//variable hiding. //the necessary 3 arguments to it
this.breed = breed; //constructor.
this.age = age; Dog labDog= new Dog("Labrador",2,"Fawn");
this.colour = colour; labDog.showProperties();
} }
//the following method prints the properties of the }
//Dog object passed to it as anargument.
public void showProperties()
{
System.out.println("The properties of this dog
are as follows :");
System.out.println("Breed :"+this.breed);
System.out.println("Age :"+this.age);
System.out.println("Colour :"+this.colour);
Mrs. Apurwa Barve
this keyword (IMCC)

The output of the previous eg is :

The properties of this dog are as follows :


Breed :Labrador
Age :2
Colour :Fawn
Mrs. Apurwa Barve
this keyword (IMCC)

Consider following flow of the previous program :

Step 1 : We declare a class Dog with 3 instance variables. This class has a parameterized
constructor with 3 arguments. The names of these local parameters are same as those of
instance variables.

Dog Dog() - constructor

breed breed
age
age
colour
colour
Mrs. Apurwa Barve
this keyword (IMCC)

Step 2 : We create an object of Dog class, dg, and pass 3 arguments to it. Thus we invoke the
constructor. i.e Dog dg= new Dog("Labrador",2,"Fawn");

dg labDog - constructor

breed = null breed = Labrador


age =0
colour =null age = 2

colour = fawn
Mrs. Apurwa Barve
this keyword (IMCC)

Step 3 : We now need to fix the values of local variables, breed, age and colour, from within
the constructor to the instance variables, breed, age and colour of the object dg.
For this, we use the keyword ‘this’ to refer to the instance variables and assign the values
of same named local variable to instance variables.

dg - object

breed = labrador

age =2

colour = fawn

labDog() -constructor

this.breed = breed

this.age = age

this.color = colour
Mrs. Apurwa Barve
this keyword (IMCC)

If we do not use ‘this’ in the constructor then due to instance variable hiding, the
instance variables of object dg will never get the values passed as arguments. These
arguments will remain within the scope of the constructor. And instance variables will be
initialized to their default values. Hence the values do not pass from the local variables to
the instance variables. Thus it will look like below :

dg - object

breed =null

age =0

colour = null

dg() -constructor

breed=breed

age=age

colour=colour
Mrs. Apurwa Barve
Class activity - 8 (IMCC)

1. Let us code Dog class using Eclipse. Do not use this keyword first and observe which
values you see in instance variables. Now modify the code to have this keyword and
observe the change in instance variables.
Mrs. Apurwa Barve
Accessors and Mutators (IMCC)

 Encapsulation principle of OOP recommends having a wrapper around data members to


streamline access to them. This is done through Accessor and Mutator methods.
 Accessor method is the one which accesses or gets the value of a variable. Its syntax is:
public variableDataType getVariableName(){
return instanceVariable;
}
 Mutator method is the one which mutates or sets value of a variable. Syntax is :
public void setVariableName(variableDataType tempVariable)
{
this.instanceVariable = tempVariable;
}
 Following steps need to be carried our for having accessors and mutators in our class:
a. Declare ALL instance variables as PRIVATE.
b. Define PUBLIC accessor methods for EACH instance variable.
c. Define PUBLIC mutate methods for EACH instance variable.
Mrs. Apurwa Barve
Accessors and Mutators (IMCC)

To understand more about accessor and mutator methods,


watch AccessorMutatorMethods video
Mrs. Apurwa Barve
Class activity - 9 (IMCC)

1. As per described in the video, modify Student class to have accessor and mutator
methods and show their use.
Mrs. Apurwa Barve
Object Cloning (IMCC)

 Cloning is a way of creating an exact COPY of a given object.

 For facilitating object cloning that class needs to do 2 things: implement Cloneable
interface and override clone().

 Syntax of clone() is:

protected Object clone() throws CloneNotSupportedException

CloneNotSupportedException is thrown when a class DOES NOT implement Cloneable


interface. This is a MARKER interface.

 We can create a copy of object by calling new operator but that leads to extra overhead
and hence NOT preferred.

 Cloning is done on 2 levels namely, shallow cloning and deep cloning.

 Shallow Cloning : Watch video ShallowCloning

 Deep Cloning : Watch video DeepCloning


Mrs. Apurwa Barve
Cloning (IMCC)

To understand more about cloning watch, Cloning

To understand more about Shallow cloning watch,


ShallowCloning

To understand more about Deep cloning watch, DeepCloning


Mrs. Apurwa Barve
Generics (IMCC)

Read

https://www.tutorialspoint.com/java/java_generics.htm#:~:text=Java%20Generic%20meth
ods%20and%20generic,invalid%20types%20at%20compile%20time.
Mrs. Apurwa Barve
What we learnt? (IMCC)
Mrs. Apurwa Barve
Quiz (IMCC)

 Kindly take the quiz of this chapter to assess your knowledge of concepts covered in this
chapter.

Mrs. Apurwa Barve (IMCC)


Mrs. Apurwa Barve
Extra reading (IMCC)

 https://techvidvan.com/tutorials/java-garbage-collection/
 https://stackify.com/what-is-java-garbage-collection/
 https://www.javaworld.com/article/3512039/does-java-pass-by-reference-or-pass-
by-value.html
 https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
 https://www.edureka.co/blog/shallow-and-deep-copy-java/
 Read about cloning v/s copy constructor
https://www.baeldung.com/java-copy-
constructor#:~:text=Copy%20Constructor%20vs.&text=In%20Java%2C%20we%20can%
20also,is%20much%20easier%20to%20implement.&text=The%20clone%20method%2
0returns%20a%20general%20Object%20reference.
Thank you!

Mrs. Apurwa Barve (IMCC)

You might also like