Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

CHAPTER 2: STATIC

MODIFIER AND
INTERFACES
ADVANCED OBJECT–ORIENTED PROGRAMMING
Introduction to static
■ The static modifier is included in a field or method declaration
■ Static fields are also known as class fields and static method is also known as class method
■ No instance of the class is required in order to use the static fields or methods — they are associated with
the class and not an individual object.
■ When something is not static (instance), it means that there is an instance of it for each instance of the class.
Each one can change independently.
■ When something is static, it means there is only one copy of it for all instances of the class, so changing it
from any location affects all others.
■ Static variables/methods typically use less memory because there is only one copy of them, regardless of
how many instances of the class you have.
■ Making a method static means it cannot be overridden. So if you have a method you want to override in a
subclass, then don't make it static.
■ If you need only one copy of it, make it static. If you need a copy per instance, then make it non static.
■ By declaring a method using the static keyword, you can call it without first creating an object
because it becomes a class method
Introduction to static
Introduction to Static Fields
• The fields itemId and itemName are normal non-static
fields. When an instance of an Item class is created, these
fields will have values that are held inside that object. If
public class Item { another Item object is created, it too will have itemId and
itemName fields for storing values.
  //static field uniqueId • The uniqueId static field, however, holds a value that will
  private static int uniqueId = 1;
be the same across all Item objects. If there are 100 Item
  private int itemId; objects, there will be 100 instances of the itemId and
  private String itemName; itemName fields, but only one uniqueId static field.
  public Item(String itemName)
• In the example, uniqueId is used to give each Item object
  { a unique number. This is easy to do if every Item object that
    this.itemName = itemName; is created takes the current value in the uniqueId static
    itemId = uniqueId;
    uniqueId++;
field and then increments it by one. The use of a static field
  } means that each object does not need to know about the other
} objects to get a unique id. This could be useful if you wanted
to know the order in which the Item objects were created.
Static Fields(example1)
class Employee
{
int empId;
String empName;
static String companyName = "TCS";
//constructor to initialize the variable Output:
Employee(int id, String name){
empId = id; 218 Kushal TCS
empName = name;
} 635 Bhumika TCS
//method to display values 147 Renuka TCS
void display()
{
System.out.println(empId+" "+empName+" "+companyName);
}
}
//class to create and display the values of object
public class StaticVariable
{
public static void main(String args[])
{
Employee EmployeeObj = new Employee(218,"Kushal");
Employee EmployeeObj1 = new Employee(635,"Bhumika");
Employee EmployeeObj2 = new Employee(147,"Renuka");
//calling display method
EmployeeObj.display();
EmployeeObj1.display();
EmployeeObj2.display();
}
}
Introduction to Static Methods
• Static methods in Java belong to classes, unlike other classes it
doesn’t belong to the instance of the class. These are declared with the
keyword “static” when defining a method
• This method belongs to the class and not to the object.
• It can access only static data. It can not access instance variables.
• A static method can call only static methods, non-static methods are
not called by a static method.
• This method is can be accessed by the class name it doesn’t need any
object.
Non Static Method/fields(Example 1)
public class Item {
  private String itemName;
 
 public Item(String itemName) {
     this.itemName = itemName;
   }
  public String getItemName() { OUTPUT ?
     return itemName;
   }
}
 public class StaticExample {
  public static void main(String[] args) {
    Item catFood = new Item("Whiskas");
    System.out.println(catFood.getItemName());
 }
}
Introduction to Static Methods(Example 1)
//Java Program to demonstrate the use of a static method.
class Employee {
int empId;
String empName;
static String companyName = "TCS";
//static method to valueChange the value of static variable
static void valueChange(){
companyName = "DataFlair"; Output:
}
//constructor to initialize the variable
Employee(int id, String name){ 218 Kushal DataFlair
empId = id;
empName = name;
635 Bhumika DataFlair
} 147 Renuka DataFlair
//method to display values
void display(){
System.out.println(empId+" "+empName+" "+companyName);
}
}
//class to create and display the values of object
public class Demo {
public static void main(String args[]){
Employee.valueChange();//calling valueChange method
//creating objects
Employee EmployeeObj = new Employee(218,"Kushal"); A static method can be called through its class name
Employee EmployeeObj1 = new Employee(635,"Bhumika");
Employee EmployeeObj2 = new Employee(147,"Renuka");
Non-static method must be called through its instance name
//calling display method
EmployeeObj.display();
EmployeeObj1.display();
EmployeeObj2.display();
}
}
The static block is a "static initializer".
).

Static initializer
The static initializer is a static {} block of code inside java class, and run only one time before the constructor
or main method is called. It's automatically invoked when the class is loaded, and there's no other way to invoke
it.

It is possible to use static keyword to cover a code block within a class which does not belong to any function.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when
the class is loaded (actually, when it's resolved, but that's a technicality).
The code block with the static modifier signifies a class initializer; without the static modifier the code block is
an instance initializer.
Instance initializers are executed in the order defined when the class is instantiated, immediately before the
constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable, which you are not able to access from the
static initializer block. This will fail to compile with the error "non-static variable cannot be referenced from a static
context".
If you also remove static from the initializer block, it then becomes an instance initializer and so int a is
initialized at construction.
Static initializer (example1)
Executed before the constructor is executed

public class StaticBlock {


public StaticBlock() { Output:
System.out.println("StaticBlock constructor.."); Static block...
} StaticBlock constructor..
static {
StaticBlock constructor..
System.out.println("Static block...");
}
} Static block is executed only once
public class StaticBlockMain { before the constructor is invoked.
public static void main(String[] args) { It can also be written the
StaticBlock staticBlockOne = new StaticBlock(); constructor
StaticBlock staticBlockTwo = new StaticBlock();
}
}
Static initializer (example1)
Executed before main method is executed
public class StaticBlock
{ Output:
static String sentence; Welcome to DataFlair
static int number; Value of Integer: 69

.
static
{
sentence = "Welcome to DataFlair";
number = 69;
}

public static void main(String args[])


{
System.out.println(sentence);
System.out.println("Value of Integer: "+number);
}
}
Non-Static/instance initializer (example1)
public class InitializerExample {
{ System.out.println("Initilizer block one"); } Output:
public static void main(String[] args) { Initilizer block one
InitializerExample exampleOne = new InitializerExample(); Initilizer block one
InitializerExample exampleTwo = new InitializerExample(); Main method
System.out.println("Main method");
notes: Initializer block has
}
executed twice because created two
} objects for InitializerExample class.
Initializer block will be invoked
upon object creation. This block is
invoked how many time objects are
created.
Non-Static/instance initializer (example2)
public class InitializerExample {
{ System.out.println("Initilizer block one"); } Output:
Initilizer block one
Initilizer block two
InitializerExample() { 1234
System.out.println("1234"); Initilizer block one
} Initilizer block two
{ System.out.println("Initilizer block two"); }
1234
Main method
public static void main(String[] args) {
InitializerExample exampleOne = new InitializerExample();
InitializerExample exampleTwo = new InitializerExample();
System.out.println("Main method");
}
}
Non-Static/instance initializer (example3)
public class InitializerExample {
Output:
{ System.out.println("Initilizer block one"); Initilizer block one
} InitializerExample Constructor
Initilizer block one
InitializerExample Constructor
public InitializerExample(){ System.out.println("InitializerExample Main method
Constructor");
}
public static void main(String[] args) {
InitializerExample exampleOne = new InitializerExample();
InitializerExample exampleTwo = new InitializerExample();
System.out.println("Main method");
}
}
The static block is a "static initializer".
).

Static Class (just to inform)


■ A class can be defined a class static only if it is a nested class.

■ Nested static class doesn’t need any reference of the Outer class. Non-
static members are not accessed by a static class.
Static Class(example1)
class OuterClass{ public class StaticClass {
private static String messageToReaders = "Hello Readers! Welcome to public static void main(String args[]){
DataFlair"; // instance of nested Static class
// Static nested class OuterClass.NestedStaticClass printer = new
public static class NestedStaticClass{ OuterClass.NestedStaticClass();
public void myMessage() {
System.out.println("Message from nested static class: " + // call non static method of nested static class
messageToReaders); printer.myMessage();
} OuterClass outer = new OuterClass();
} OuterClass.InnerClass inner = outer.new InnerClass();
// non-static nested class
public class InnerClass{ // calling non-static method of Inner class
public void display(){ inner.display();
System.out.println("Message from non-static nested class: "+ OuterClass.InnerClass innerObject = new
messageToReaders); OuterClass().new InnerClass();
} innerObject.display();
} }
} }
What is a Java Interface?
■ It is an abstract type used to designate a set of abstract methods for classes to
implement.
■ when a class implements an interface, it must inherit all of the abstract methods
declared within
■ Both interfaces and classes contain methods. They are more different than they are
the same, however: an interface lacks constructors, contains exclusively abstract
methods (no method implementation), and exclusively final and static fields.
■ It is used to achieve multiple inheritance.
■ It is used to achieve loose coupling.
■ All the methods are public and abstract. And all the fields are public, static,
and final.
Interfaces Syntax

To Define Interface

interface interfaceName {
//methods
}
Examples of Interfaces
To Implement Interface

public class SkeletonNPC implements Enemy


To Define Interface { public void speak()
{ System.out.println("Skeleton shrieks at the player."); }

interface Enemy{ public void moveTo()


public void speak(); { System.out.println("Skeleton runs towards the player."); }
public void moveTo(int x, int y);
public void attack(entity e); public void attack()
public void heal(int amt); { System.out.println("Skeleton attacks the player."); }
public void eventOnDeath();
} public void heal()
{ System.out.println("Skeleton heals itself with a
potion.");}

public void throwRock() { System.out.println("Skeleton throws


a rock at the enemy."); }

public void eventOnDeath() { System.out.println("Skeleton


falls apart and drops an item."); }
}
Interface
• Any class that implements this interface in your game must speak, move, attack, heal, and
have an event after they’re defeated.

• Numerous enemy classes might have their own unique attributes, but each and every one
that implements Enemy interface must adhere to the methods listed.

• Certain enemies might speak differently, attack differently, or do something differently after
defeat, but they will all at least do those things.

•  The SkeletonNPC class implements all the methods seen in interface Enemy, from speaking,
moving, attacking, and more.

• The SkeletonNPC class also has another behavior, throwRock(), which is unique to that
class. It is not included in interface Enemy, because only the SkeletonNPC enemy should
have this behavior.
Why Interface?
• It is used to achieve total abstraction.
• Since java does not support multiple inheritance in case of class, but by using interface it
can achieve multiple inheritance .
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction. So the question arises why use interfaces
when we have abstract classes?
• The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.

// A simple interface
interface Player
{
    final int id = 10;
    int move();
}
asWheels(); public void hasEngine(); } public interface Car extends Vehicles { public void hasDoors(); public void hasAirbags(); public void hasRoof(); } public interface Motorcycle extends Vehicles { public void hasPedal(); public void ha

Extending Interface
■ It’s possible to have an interface extends another interface. Just like classes, the extended child
interface will inherit the abstract methods specified in the parent interface.
■ To extend an interface, you simply need to use the extends keyword, followed by a list of parent
interfaces, separated by commas.

public interface Vehicles { • the Car and Motorcycle interfaces extend the
public void hasWheels(); Vehicles interface. The Vehicles interface contains
public void hasEngine(); } two methods: hasWheels() and hasEngine(). Any
class that implements interface Vehicles must meet
public interface Car extends Vehicles these two requirements.
{
public void hasDoors(); • If a class implements interface Car, then it must
public void hasAirbags(); adhere to the three methods laid out in the extension
public void hasRoof(); } – hasDoors(), hasAirbags(), and hasRoof()
– plus the methods indicated in interface Car’s
public interface Motorcycle extends parent interface, Vehicles.
Vehicles {
public void hasPedal();
public void hasHandlebars();
Implementing Multiple Interfaces
• Multiple inheritance by interface occurs
• if an interface itself extends multiple interfaces
• if a class implements multiple interfaces or

• if an interface itself extends multiple interfaces


public interface Car extends Vehicles, Belongings, Transit

• The above example indicates that the child interface Car is an


extension of the Vehicles interface we declared previously, as well
as an interface called Belongings, and an interface called Transit.
Any methods declared in the Belongings and Transit interfaces will
be inherited by the child interface Car.
Implementing Multiple Interfaces
• Multiple inheritance by interface occurs if a class implements multiple interfaces or also if
an interface itself extends multiple interfaces.
interface AnimalEat { public class Demo {
   void eat();    public static void main(String args[])
} {
interface AnimalTravel {       Animal a = new Animal();
   void travel();       a.eat();
}       a.travel();
class Animal implements AnimalEat,    }
AnimalTravel { }
   public void eat() {
      System.out.println("Animal is
eating");
   } Output
   public void travel() { Animal is eating
      System.out.println("Animal is Animal is travelling
travelling");
   }
}
Difference between Class and Interface

Class Interface

In class, you can instantiate variable and In an interface, you can't instantiate
create an object. variable and create an object.

Class can contain concrete(with The interface cannot contain concrete(with


implementation) methods implementation) methods

The access specifiers used with classes are In Interface only one specifier is used-
private, protected and public. Public.
Why is an Interface required?

The class "Media Player" has two subclasses: CD player and DVD
player. Each having its unique implementation method to play
music.

Another class "Combo drive" is inheriting both CD and DVD (see


image below). Which play method should it inherit? This may cause
serious design issues. And hence, Java does not allow multiple
inheritance.
Why is an Interface required?

Suppose you have a requirement where class "dog"


inheriting class "animal" and "Pet“. But you cannot extend
two classes in Java. So what would you do? The solution
is Interface.

Class Dog can extend to class "Animal" and implement


interface as "Pet"
Must know facts about Interface
• A Java class can implement multiple Java Interfaces. It is necessary that the class must
implement all the methods declared in the interfaces.
• Class should override all the abstract methods declared in the interface
• The interface allows sending a message to an object without concerning which classes it
belongs.
• Class needs to provide functionality for the methods declared in the interface.
• All methods in an interface are implicitly public and abstract
• An interface cannot be instantiated
• An interface reference can point to objects of its implementing classes
• An interface can extend from one or many interfaces. Class can extend only one class but
implement any number of interfaces
• An interface cannot implement another Interface. It has to extend another interface if
needed.
• An interface which is declared inside another interface is referred as nested interface
• At the time of declaration, interface variable must be initialized. Otherwise, the compiler
will throw an error.
• The class cannot implement two interfaces in java that have methods with same name but
different return type.

You might also like