0% found this document useful (0 votes)
24 views18 pages

Lecture 04 Oop210

This document discusses keywords in object-oriented programming in Java, specifically this, final, and static. The this keyword is used as a reference variable to the current object and has several uses including referring to instance variables, invoking instance methods, calling constructors, passing the current object as an argument, and returning the current object. The final keyword is used to restrict modification and has three main uses - declaring constant variables, preventing method overriding, and preventing class inheritance. The static keyword defines a static element that is common to all instances rather than being instantiated separately. This allows for static methods, variables, blocks and other elements that are shared among all object instances.

Uploaded by

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

Lecture 04 Oop210

This document discusses keywords in object-oriented programming in Java, specifically this, final, and static. The this keyword is used as a reference variable to the current object and has several uses including referring to instance variables, invoking instance methods, calling constructors, passing the current object as an argument, and returning the current object. The final keyword is used to restrict modification and has three main uses - declaring constant variables, preventing method overriding, and preventing class inheritance. The static keyword defines a static element that is common to all instances rather than being instantiated separately. This allows for static methods, variables, blocks and other elements that are shared among all object instances.

Uploaded by

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

Object-Oriented Programming

Lecture 4 – this, final, and static keywords

Ralph Tambala

MUST . CSIT

Lecture 4 1 / 18
Outline

1 this Keyword

2 final Keyword

3 static Keyword

Lecture 4 2 / 18
this Keyword

this Keyword

In Java, you will often encounter or use this this keyword. It is commonly
used as a reference variable that refers to the current object.

Below are six usage of this:


1 this to refer instance variable.
2 this to invoke instance method.
3 this() can be used to invoke current class constructor.
4 this can be passed as an argument in the method call.
5 this can be passed as argument in the constructor call.
6 this can be used as return value.

Lecture 4 3 / 18
this Keyword

this Keyword
this to refer instance variable

Accessing class level variable (instance variable) using this keyword is the
most common use of this keyword.

Syntax: this.variableName
1 class Student {
2 String name ;
3 public void setName ( String name ) {
4 this . name = name ; // name = name ; is wrong !
5 }
6 }

Here, this has been used in the event that we use same name for local
variable and instance variable. Otherwise, JVM will use local variable
always, and it will not set the value to instance variable.

Lecture 4 4 / 18
this Keyword

this Keyword
this to invoke instance method

this can be used for invoking instance methods within the same class.

Syntax: this.methodName
1 class Greeting {
2 public void hello () {
3 System . out . println ( " Muli uli ? " ) ;
4 }
5 public void greet ( String name ) {
6 this . hello () ;
7 hello () ; // optionally , works too without this
8 }
9 }

If one chooses to not use this keyword, JVM always calls the method
from same class by default.

Lecture 4 5 / 18
this Keyword

this Keyword
this to invoke current class constructor

this keyword can also be used to call constructor of same class. When we
have several constructors with different parameters, we can use the this
keyword to reuse an existing constructor.

Syntax: this() // this(arguments)


1 class Student {
2 String name ;
3 Student () {}
4 Student ( String name ) {
5 this () ; // calls Student () constructor
6 this . name = name ;
7 }
8 }

Lecture 4 6 / 18
this Keyword

this Keyword
this to return current class instance

We can return this keyword as a statement from the method. In such


case, return type of the method must be the class type.

Syntax: return this


1 class Student {
2 String name ;
3 int age ;
4 Student setDetails ( String name , int age ) {
5 this . name = name ;
6 this . age = age ;
7 return this ; // returns class instance of Student
8 }
9 }

Lecture 4 7 / 18
this Keyword

this Keyword
this to pass as an argument in the method

this keyword can also be passed as an argument in the method.

Syntax: methodName(this)
1 class Student {
2 String name ;
3 void msg ( Student st ) {
4 System . out . println ( " Obj created ! " ) ;
5 }
6 void report () {
7 msg ( this ) ; // passing this as an argument
8 }
9 public static void main ( String [] args ) {
10 Student student = new Student () ;
11 student . report () ;
12 }
13 }

Lecture 4 8 / 18
this Keyword

this Keyword
this as an argument in the constructor call

this can be passed as argument to constructor of current class as well as


to constructor of another class.
1 public class City {
2 private String name ;
3 private Country country ;
4 public City ( String name , Country country ) {
5 this . name = name ;
6 this . country = country ;
7 }
8 }
9 public class Country {
10 private City capital ;
11 public void setCapital ( String cityName ) {
12 // passing country class object using this keyword
13 City capital = new City ( cityName , this ) ;
14 this . capital = capital ;
15 }
16 }
Lecture 4 9 / 18
final Keyword

final Keyword

final is a keyword that is used to restrict the user in Java programming.


It is a non-access modifier that is only applicable to a variable, method, or
class.

final keyword can be used when declaring an entity. Using the final
keyword means that the value cannot be modified in the future.

It has three different uses:


1 final variable used to declare a constant.
2 final method used to prevent method overridding.
3 final class used to prevent class inheritance.

Lecture 4 10 / 18
final Keyword

final Keyword
Declaration of Final Variables

A final keyword can be applied to local variables, instance variables, and


static variables.
Syntax: final dataType variableName = value;

1 public class A {}

1 public class B {
2 final private int a = 20; // ok
3 a = 30; // throws an error
4 final int b ; // blank final
5 B () {
6 b = 30; // ok , initialization inside constructor
7 }
8 final A myA = new A () ;
9 A theirA = new A () ;
10 myA = theirA ; // error , myA was declared as final
11 }
Lecture 4 11 / 18
final Keyword

final Keyword
Declaration of Final Methods

A method declared with the final keyword cannot be overridden or


hidden by subclasses.
Syntax: final dataType variableName = value;
1 class Animal {
2 final void do () {
3 System . out . print ( " Move " ) ;
4 }
5 }
6 class Bird extends Animal {
7 final void do () { // overriding " do " throws an error
8 System . out . print ( " Fly " ) ;
9 }
10 }

Basically, without final keywords the example above would not produce an
error. We will discuss in detail what method overriding and keyword
extends work when we look at Polymorphism.
Lecture 4 12 / 18
final Keyword

final Keyword
Declaration of Final Classes

Java classes declared as a final cannot be extended (inherited). If you do


not want to be a subclass, declare it final.

There are two ways to make a class as final:


1 Use the final keyword in the class declaration.
1 final class Animal { }
2 class Bird extends Animal { } // error

2 Use private keyword in the class declaration.


1 private class Animal { }
2 class Bird extends Animal { } // error

We will discuss in detail about inherited classes when we look at


Inheritance.

Lecture 4 13 / 18
final Keyword

final Keyword
Important Notes

Here are some important points to take note of when using the final
keyword:
1 A class constructor cannot be final.
2 A block cannot be final.
3 A local final variable must be initialized at the time of declaration.
4 We cannot change the value of a final variable after initialization.
5 A final method cannot be overridden.
6 A final class cannot be inherited.
7 We can create the object for a final class but cannot extend it.
8 If the method parameters are declared as final, their values
(arguments) cannot be changed.
.
Lecture 4 14 / 18
static Keyword

static Keyword
If a field (class, block, method or variable) is declared static, then exactly
a single copy of that field is created and shared among all instances of that
class.

Static members are common for all the instances(objects) of the class but
non-static members are separate for each instance of class.
1 class Demo {
2 static int num ;
3 static void work () { // static method
4 System . out . println ( " Some task eh ! " ) ;
5 }
6 static { // a static block
7 counter = 11;
8 }
9 public static void main ( String [] args ) {
10 work () ; // called without creating object
11 }
12 }
Lecture 4 15 / 18
static Keyword

static Keyword (1)


Practical Use – example

Imagine you want to generate an id for each who registers on your website
dynamically. A first user to sign up get id = 1, second user gets id = 2,
and so on.
Basically, we can implement the code as follows:
1 class User {
2 static int counter = 0;
3 int id ;
4 User () {
5 id = counter ++;
6 }
7 public static void main ( String [] args ) {
8 User user1 = new User () ;
9 User user2 = new User () ;
10 System . out . println ( " user1 ID = " + user1 . id + " \ n " +
11 " user2 ID = " + user2 . id ) ;
12 }
13 }
Lecture 4 16 / 18
static Keyword

static Keyword (2)


Practical Use – example

The output of the previous program is :


user1 ID = 1
user2 ID = 2
Explanation:
Line 2 we are initializing a static variable counter to 0
Line 5, inside our constructor we are assigning instance variable id to
an increment of counter. Here, id will be getting a value of plus 1
the current value of counter.
Line 8, creating object user1 will call the constructor we defined on
Line 4–6 setting its id to 1 since its the first object to be called and
counter value is now 1.
Line 8, creating object user1 will call the constructor we defined on
Line 4–6 setting its id to 2 since counter value is now 2.
Lecture 4 17 / 18
static Keyword

practice

Lecture 4 18 / 18

You might also like