Keywords and Classes
Keywords and Classes
Keywords and Classes
Techniques-I
Lecture 9: This, Super & Final Keywords
Contents
• Object class
• super keyword
• final keyword
• final class
• static keyword
• this keyword
Object Class
There is one special class, called Object, defined by Java.
All other classes are subclasses of Object. i.e., Object is a
super-class of all other classes.
A reference variable of type Object can refer to an object of
any other class.
The Object class defines the basic state and behavior that all
objects must have.
Arrays are implemented as classes, so a variable of type
Object can also refer to any array.
In Object class, getClass( ), notify( ), notifyAll( ), and wait( )
are declared as final.
Methods in Object class
‘final’ Keyword
• ‘final’ keyword is used to:
– declare variables that can be assigned value only once.
final type identifier = expression;
class T2 {
static int triple (int n)
{return 3*n;}
}
class T1 {
public static void main(String[] arg)
{
System.out.println( T2.triple(4) );
T2 x1 = new T2();
System.out.println( x1.triple(5) );
}
}
• Methods declared with “static” keyword are called “class
methods”.
• Otherwise they are “instance methods”.
• Static Methods Cannot Access Non-Static Variables.
• The following gives a compilation error, unless x is also static.
class T2 {
int x = 3;
static int returnIt () { return x;}
}
class T1 {
public static void main(String[] arg) {
System.out.println( T2.returnIt() ); }
}
Properties of static & non-static method
‘this’ Keyword
• 'this' is used for pointing the current class instance.
• Within an instance method or a constructor, this is a reference to
the current object — the object whose method or constructor is
being called.
class ThisDemo1{
int a = 0;
int b = 0;
ThisDemo1(int x, int y)
{
this.a = x;
this.b = y;
}