Professional Documents
Culture Documents
Chapter 2 - STATIC MODIFIER AND INTERFACE Final Version
Chapter 2 - STATIC MODIFIER AND INTERFACE Final Version
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
.
static
{
sentence = "Welcome to DataFlair";
number = 69;
}
■ 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
• 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
Class Interface
In class, you can instantiate variable and In an interface, you can't instantiate
create an object. variable and create an object.
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.