You are on page 1of 33

Classes and Objects

Module - 3
Module – 3 Classes and Objects
Class Fundamentals – Access and non-access
specifiers-Declaring objects and assigning object
reference variables-array of objects-constructors and
destructors-usage of “this” and “static” keywords.
Classes

• A class is a user defined blueprint or


prototype from which objects are
created.
• It represents the set of properties or
methods that are common to all objects
of one type.
Creating Objects
Classname objectname = new Classname(); or
Classname objectname = new Classname(parameters);
Each of these statements has three parts
• Declaration: The code set in bold are all variable declarations that
associate a variable name with an object type.
• Instantiation: The new keyword is a Java operator that creates the
object.
• Initialization: The new operator is followed by a call to a constructor,
which initializes the new object.
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle


public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing the area of the rectangle


public int getArea() {
return width * height;
}
}
Class Components
• Modifiers: A class can be public or has default access

• Class keyword: class keyword is used to create a class.

• Class name: The name should begin with an initial letter (capitalized by convention).

• Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the

keyword extends. A class can only extend (subclass) one parent.

• Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,

preceded by the keyword implements. A class can implement more than one interface.

• Body: The class body is surrounded by braces, { }.


Example Program
class Box { class BoxDemo {
public static void main(String args[]) {
double width; Box mybox = new Box();
double height; double vol;
double depth; mybox.width = 10;
mybox.height = 20;
} mybox.depth = 15;
vol = mybox.width * mybox.height *
mybox.depth;
System.out.println ("Volume is " + vol);
}}
Constructor
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method
2) it has the same name as the name of its class
3) it is written without return type
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.
Example-Constructor
class Box { depth = 10;
double width;
double height;
}
double depth; double volume()
Box() {
{
return width * height * depth;
System.out.println("Constructing Box");
width = 10; }
height = 10; }
Java Access Modifiers

• access modifiers are used to set the accessibility


(visibility) of classes, interfaces, variables, methods,
constructors, data members, and the setter methods.
class Animal
{
public void method1() {...} //can be accessed by other classes.
private void method2() {...}//cannot be accessed by other classes.
}
Types of Access Modifier

Modifier Description

declarations are visible only within the


Default
package (other package private)

Private declarations are visible within the class only

declarations are visible within the package or


Protected
all subclasses

Public declarations are visible everywhere


this keyword
• Java “this” keyword is a reference variable that
refers to the current object.
• The main purpose of using this keyword is to solve
the confusion when we have same variable name for
instance and local variables.
Uses of this keyword
• this can be used to refer current class instance variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from
the method.
Using ‘this’ keyword to refer current class
instance variables
//Java code for using 'this' keyword to
//refer current class instance variables void display()
class Test {
//Displaying value of variables a and b
{
System.out.println("a = " + a + " b = " + b);
int a; }
int b;
public static void main(String[] args)
// Parameterized constructor {
Test object = new Test(10, 20);
Test(int a, int b)
object.display();
{ }
this.a = a; }
this.b = b;
}
Using this() to invoke current class constructor
// Java code for using this() to
// invoke current class constructor //Parameterized constructor
class Test Test(int a, int b)
{ {
int a; this.a = a;
int b; this.b = b;
System.out.println("Inside parameterized
//Default constructor constructor");
Test() }
{
public static void main(String[] args)
this(10, 20);
System.out.println("Inside default constructor \n"); {
} Test object = new Test();
}
}
Using ‘this’ keyword to return the current class
instance
//Java code for using 'this' keyword
//to return the current class instance //Displaying value of variables a and b
class Test void display()
{
{
int a;
int b; System.out.println("a = " + a + " b = " + b);
//Default constructor }
Test()
{
a = 10;
public static void main(String[] args)
b = 20; {
} Test object = new Test();
//Method that returns current class instance
object.get().display();
Test get()
{ }
return this; }
}
Using ‘this’ keyword as method parameter
class Test
{
int a;
// Method that returns current class instance
int b; void get()
// Default constructor {
Test() display(this);
{ }
a = 10;
b = 20; public static void main(String[] args)
} {
// Method that receives 'this' keyword as parameter Test object = new Test();
void display(Test obj) object.get();
{ }
System.out.println("a = " +obj.a + " b = " + obj.b); }
}
Using ‘this’ keyword to invoke current class
method
// Java code for using this to invoke current void show()
// class method {
class Test { System.out.println("Inside show function");
void display() }
{
// calling function show() public static void main(String args[])
this.show(); {
System.out.println("Inside display function"); Test t1 = new Test();
} t1.display();
}
}
Using ‘this’ keyword as an argument in the
constructor call
class A
class B
{ {
B obj; int x = 5;
B()
A(B obj) {
{ A obj = new A(this);
this.obj = obj; }

void display()
obj.display(); {
} System.out.println("Value of x in Class B : " + x);
}
} public static void main(String[] args)
{
B obj = new B();
}
}
Static Keyword
What is static
• The static keyword is used when a member variable
of a class has to be shared between all the instances
of the class.
• All static variables and methods belong to the class
and not to any instance of the class
When can we access static variable
• When a class is loaded by the virtual machine all the
static variables and methods are available for use.
• Hence we don’t need to create any instance of the
class for using the static variables or methods.
• Variables which don’t have static keyword in the
definition are implicitly non static.
Example
// when we use the class name, the class is loaded,
Class staticDemo{
direct access to a without any instance
public static int a = 100; // All instances of
staticDemo.b=22;
staticDemo have this variable as a common `
// ERROR this is not valid for non static variable
variable
staticDemo demo = new staticDemo();
public int b =2 ;
demo.b = 200;
public static showA(){
// valid to set a value for a non static variable after
System.out.println(“A is “+a);
creating an instance.
}
staticDemo.showA(); //prints 35
}
}
Class execClass{
}
public static void main(String args[]){
staticDemo.a = 35;
Static and Non-static
• We can access static variables without creating an
instance of the class
• As they are already available at class loading time, we
can use them in any of our non static methods.
• We cannot use non static methods and variables without
creating an instance of the class as they are bound to the
instance of the class.
• They are initialized by the constructor when we create
the object using new operator.
How it works
Basic Steps of how objects are created
1. Class is loaded by JVM
2. Static variable and methods are loaded and initialized
and available for use
3. Constructor is called to instantiate the non static
variables
4. Non static variables and methods are now available

• As all the non static variable are


available only after the constructor
is called, there is a restriction on
using non static variable in static

You might also like