Java/C3/Static-Methods/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of script: Static Methods

Author: Joms Antony

Keywords: Static methods, Class methods, Instance methods, Static variables


Visual Cue
Narration
Slide 1 Welcome to the Spoken Tutorial on Static Methods.
Slide 2

Learning Objectives

  • What are static methods
  • Defining static methods
  • Difference between instance methods and static methods
  • How to use static methods
In this tutorial we will learn:
  • What are static methods
  • Defining static methods
  • Difference between instance methods and static methods and
  • How to use static methods
Slide 3

Software Requirements

  • Ubuntu 14.04
  • JDK 1 .7
  • Eclipse 4.3.1
Here we are using
  • Ubuntu 14.04
  • JDK 1 .7 and
  • Eclipse 4.3.1
Slide 4

Prerequisites

  • Basic knowledge of Java and Eclipse IDE
  • Knowledge of instance variables, methods and static variables in Java
  • For relevant tutorials, please visit http://www.spoken-tutorial.org
To follow this tutorial,

You must have knowledge of basics of Java and Eclipse IDE.

You should also have the knowledge of instance variables, methods and static variables in Java.

If not, for relevant Java tutorials, please visit the link shown.

Slide 5

Static Method


  • A static method is a method which is associated with the entire class
  • It is also called a class method and is declared using the static keyword.
  • Static methods are usually used to handle static variables


A static method is a method which is associated with the entire class.


It is also called a class method and is declared using the static keyword.


Static methods are usually used to handle static variables.

In Eclipse IDE, create a project StaticMethodDemo


Now we will switch to Eclipse and create a new project called StaticMethodDemo.


Inside this project we will create the necessary classes to demonstrate the usage of Static methods.

Right click on src folder and click New-> Class and type the class name as StudentEnroll and hit Enter We will create a new class StudentEnroll.
Slide 6

Static Method – Example


Show the final shot in the slide.

(Three students enrolled and total count as 3)

Let us see how to use static methods with an example.


The example is very similar to the one which is used in the Static Variable tutorial.


Here again we are representing the StudentEnroll class.

Highlight name and id Recall that the variables name and id are handled as instance variables.
Highlight organization and total count Here the variables organization and total count are common to the entire class.


So they can be treated as static variables.

//copy and paste the code inside the class and highlight them

private String id, name;

private static int count;

private static String orgname="IIT Bombay";

Now type the following code to represent the StudentEnroll class.


Highlight static int count and static String orgname Note that there are two static variables count and orgname.
Highlight static String orgname Also note that orgname is not a static constant rather it is normal static variable.
Highlight static String orgname="IIT Bombay"; The static variable orgname is initialized as “IIT Bombay”.
click on Source -> and select Generate Constructor using Fields Now click on Source -> and select Generate Constructor using Fields.
Delete the super keyword Delete the super keyword from the generated code.
Inside the constructor, type count++;


Inside the constructor, type

count ++ semicolon

So, the count value is incremented every time an object is created.

Type

public void showData()

//copy the code and highlight it

{

System.out.println(id+" "+name+" "+orgname);

}

Now we will add a method showData( ) to this class to print the values of the variables.

So type public void showData( ).

Within brackets type the following code to print the values of id, name and organisation name.

//copy and paste the code

public static void setOrgName(String org)

{

orgname=org;

}

Now we will add the static method setOrgName.

Type the following code.

The setOrgName method represented here is a static method which can modify the value of orgname.

Any method which is used to handle static variables can be defined as a static method.

Now let us explore the differences between instance method and static method.
Slide 8

Instance Vs Static Methods

  • Instance methods can access static variables
  • A Static method can directly access and modify only static variables
Instance methods can access static variables.


Whereas a static method can directly access and modify only static variables.

Slide 8(A)
  • Instance methods are invoked only by an object
  • A static method can be invoked directly without creating an object
Instance methods are invoked only by an object.


Whereas a static method can be invoked directly without creating an object.

Slide 8(B)
  • We cannot use ‘this’ and ‘super’ keyword inside a static method.
  • These keywords refer to the instance of a particular class.
  • In a static context we can’t refer to instances of a class.
  • We cannot use ‘this’ and ‘super’ keyword inside a static method.
  • This is because these keywords refer to the instance of a particular class.
  • In a static context, we can’t refer to instances of a class.
Inside this static method type

id = “newid”;

Let us see what happens if we try to access an instance variable directly inside this static method.

Type,

id= “newid” semicolon

Hover the cursor to show the error Now an error comes up in Eclipse.

It indicates that an instance variable cannot be accessed directly inside a static method.

Comment the statement So let us comment this line and proceed.
//Copy and paste the code and highlight according to narration

public static void showOrgData()

{

System.out.println("\nORGANISATION DATA");

System.out.println("Name:"+orgname);

System.out.println("Total Students Enrolled:"+count);

}

Now we will add one more static method showOrgData.


These statements print the values of orgname and count.

click New-> Class and then type name as Demo. Now right click on the default package, click New-> Class and then type the name as Demo.


Inside this class we will have the main method.


So type main and then press Ctrl+space to generate the main method.

We will create a few objects of StudentEnroll class to represent student enrollments.
//Copy the code to create objects

StudentEnroll s1=new StudentEnroll("IT101","ADIL");


StudentEnroll s2=new StudentEnroll("CS101","AMAL");


StudentEnroll s3=new StudentEnroll("CS101","CAROL");

So type the following code to create 3 objects s1, s2 and s3.
(Copy the code)

s1.showData();

s2.showData();

s3.showData();

Now let us invoke the showData method to print the enrollment details.

Type the following code to invoke showData method on s1, s2 and s3.

(Copy and paste)

StudentEnroll.showOrgData();

Let us also invoke the method showOrgData to print the values of orgname and count.


Since it is a static method we can invoke it directly using its class name.


To do so, type this code.

Click on Run button Now let us run the Demo program.
Highlight

IT101 ADIL IIT Bombay

We can see that the values of the variables corresponding to s1 i.e IT101, ADIL and IIT BOMBAY gets printed.
Highlight CS101 AMAL IIT Bombay

CS101 CAROL IIT Bombay

Similarly the values corresponding to s2 and s3 are also printed.
Box IIT BOMBAY Note that the value of orgname ie IIT BOMBAY is common for s1, s2 and s3.

orgname and count are printed separately by the static method showOrgData.

Highlight Name:IIT Bombay Note that the organisation name is printed as IIT Bombay.

Highlight Total Students Enrolled:3

The value of the number of student enrollments is printed as 3, as we have already created 3 objects.
A static method can be invoked directly by the class name itself.


Now let us invoke the static method setOrgName.

Type

StudentEnroll.setOrgName("IIT Mumbai");

We will change the organisation name from “IIT Bombay” to “IIT Mumbai”.

So type the following code.

(Copy the code)

s1.showData();

s2.showData();

s3.showData();

Now let us once again invoke the showData method on s1, s2 and s3 to print the enrollment details.


For that type the following code again.

Type

StudentEnroll.showOrgData();

Once again, let us invoke the method showOrgData to print the values of orgname and count.


To do so, type this code.

Click on Run button Now run the Demo program again.
Box IIT Mumbai We can see that the organisation name is changed to “IIT Mumbai”.
Switch to slides Let us come back to slides.
Slide 11

Passing an object reference

  • Object references can be passed to a static method.
  • This way a static method can access the instance variables of that particular object.
Object references can be passed to a static method.


This way a static method can access the instance variables of that particular object.

Switch to Eclipse

Go to StudentEnroll class

Let us try it in our code.


Switch to Eclipse and go to the StudentEnroll class.

In the setOrgName method,


After String org, type

comma StudentEnroll s

Now in the setOrgName method, pass another argument as an object of StudentEnroll class.


So after String org, type

comma StudentEnroll s

uncomment id = "newid" Now inside this method, uncomment id = "newid"
Type s.id="newid"; And instead of id, type s.id
Go to the Demo class Now go to the Demo class.
In the StudentEnroll.setOrgName("IIT Mumbai");

after “IIT Mumbai”, type comma s1

Let us modify the function call to setOrgName method by passing the StudentEnroll object s1.


So here, after “IIT Mumbai”, type comma s1.

Click on Run button Now run the Demo program again.
Highlight id “newid” We can see that the value of id for s1 has changed to “newid”.
Slide 12

Summary

  • What is a static method and when it is used
  • How to differentiate static methods and instance methods
  • How to create and invoke static methods
Let us summarize.

In this tutorial we have learnt about

  • What is a static method and when it is used
  • How to differentiate static methods and instance methods and
  • How to create and invoke static methods
This assignment is a continuation of the Static variable assignment.


Make sure that you have completed the Static variable assignment.


We will highlight only the modifications here.

Slide 13
  • Design a class CarService to represent a Car Service Station
  • This class should contain variables to represent the following
    • Name of the Service Station
    • Car make, model, regno and status
    • No of Cars in for Service
    • No of cars out after Service

( Highlight “status” )


( Highlight “No of cars out after service” )

Here we have a variable to represent “status”.


It is used to indicate whether the car is “in” for service or “out” after service


We will also have another variable to represent

No of cars out after Service

Slide 13 A
  • Define a method service( Car c) which updates the status to ”out”


Accordingly it modifies the values for

  • No of Cars in for Service
  • No of Cars out after Service
  • Define a method show( ) to print the car details
Define a method service( Car c) which updates the status to ”out”.


Accordingly it modifies the values for

  • No of Cars in for Service
  • No of Cars out after Service

Also define a method show( ) to print all the car details.

Slide 13 B
  • Identify the instance variables and static variables
  • Also Identify the instance methods and static methods
  • Define a constructor to initialise the values for Car make, model, regno and status


( Highlight “static method” )

As before, we need to perform the following as listed.


Note that we have to identify and define the static method as required.

Slide 13 C
  • Also create a Demo class containing the main method


Inside the main method-

  • Create a few objects of CarService
  • Invoke the service( ) method on some of them
  • Invoke the show( ) method using all the objects and verify the results
Also create a Demo class.


Inside the main method,

Create a few objects of CarService.

Invoke the service( ) method on some of them.

Invoke the show( ) method using all the objects and verify the results.

About Project

(retain the slide as in TEX file)

The video at the following link summarizes the Spoken Tutorial Project.


Please download and watch it.

About Workshops

(retain the slide as in TEX file)

The Spoken Tutorial Project team

• Conducts workshops using spoken tutorials and

• Gives certificates on passing the online tests


For more details, please write to us.

About NMEICT

(retain the slide as in TEX file)

Spoken Tutorial Project is funded by the NMEICT, MHRD, Government of India.


More information on this Mission is available at the link shown.

Contributor slide

(retain the slide as in TEX file)

This script has been contributed by:

Dept. of Information Technology, Amal Jyothi College of Engineering.


This is Priya from IIT Bombay, thanks for joining.

Contributors and Content Editors

Nancyvarkey, Priyacst