Java #11 - Class and Object (Part -1)
Class & Object | Methods | Constructors | Example - Stack Class
Class & Object
Class defines a new data type (it contains attribute and method). Once defined, this new type can be used to create objects of that type.
Class is a template for an object and an object is an instance of a class.
Syntax to declare class
class classname{
//instance variables declaration
type instance-variable1;
type instance-variable2;
//method declaration
type methodname(parameters){
//body of method
}
}
The data or variables defined within the class are called instance variables. They are called instance variables because each instance (object) of the class contains its own copy of the variables. Thus, the data for one object is separate and unique from the data for another.
The code is contained within methods.
The method and variables defined within a class are called members of the class.
In general, it is the method that determines how class data can be used.
Example
- Create a class Box with three instance variables: width, height, and depth of type double. The below code will create a new data type "Box".
class Box{
double width;
double height;
double depth;
}
To create an object of this class first we need to create a variable of class type and create a physical copy of the object and assign it to that variable using "new" operator.
The new operator dynamically allocates (allocate at run time) memory for an object and returns a reference to it and this reference is stored in the class variable. This reference is the address in memory of the object allocated by the new.
class-var = new classname();
class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The classname followed by parenthesis specifies the constructor of the class.
A constructor defines what occurs when an object of a class is created.
In the below code, we are creating myBox as a class variable which holds the memory address of the object created using a new operator.
Box myBox = new Box(); // new Box() will create an instance of class which will be assigned to refrerence variable myBox
Set instance variables of myBox reference using the dot operator
myBox.width = 100; // the dot operator links the reference of object with the name of instance variables.
Below is the complete code to declare the Box class and create an object and access its members using the dot operator.
class Box {
double width;
double height;
double depth;
}
public class BoxDemo {
public static void main(String[] args) {
Box myBox = new Box();
myBox.width = 10;
myBox.height = 15;
myBox.depth = 20;
double volume = myBox.width * myBox.height * myBox.depth;
System.out.println("Volume is "+ volume);
}
}
Assigning Object Reference Variable
Consider below the line of code below where b2 is assigned with b1
Box b1 = new Box();
Box b2 = b1;
In the above assignment, b1 and b2 both refer to the same object i.e. changes any changes made to the object through b2 will affect the object to which b1 is referring.
When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.
What will happen in below code?
Box b1 = new Box();
Box b2 = b1;
b1 = null;
Here b1 has been set to null but b2 still points to the original object.
class Box {
double width;
double height;
double depth;
}
public class BoxDemo {
public static void main(String[] args) {
Box b1 = new Box();
b1.height = 10;
Box b2 = b1;
System.out.println(b1); //both address are same
System.out.println(b2);
b2.height = 20;
System.out.println(b1.height);
b1 = null;
System.out.println(b2.height);
System.out.println(b1); // it is null
System.out.println(b2); // still pointing to object
}
}
Output
oop.Box@66d33a
oop.Box@66d33a
20.0
20.0
null
oop.Box@66d33a
Methods
An object consists of a state and behaviour. A method is the behaviour of an object.
Java method syntax
type methodName(paramter-list){
//body of method
return value;
}
type specifies the type of data returned by the method.
The name of the method can be any legal identifier other than those already used by other items within the current scope.
The parameter-list is a sequence of type and identifier pairs separated by a comma.
If the type is not void then the method has returned some value using the return statement and this should be the last statement in the method.
Below are examples of methods with parameters
int square(int i){
return i * i;
}
Difference between parameter and argument
A parameter is a variable defined by a method that receives a value when the method is called. In the above code block, i is a parameter.
An argument is a value that is passed to a method when it is invoked. For example square(100) passes 100 as an argument.
Constructors
A constructor initializes an object immediately upon creation. Once defined, the constructor is automatically called when the object is created before the new operator completes.
It has the same name as the class and is syntactically the same as the method.
It has no return type. This is because the implicit return type of a class constructor is the class type itself.
this keyword is used to refer to the current object.
class Box{
int height;
int width;
int depth;
Box(int h, int w, int d){
this.width = w;
this.height = h;
this.depth = d;
}
}
class BoxDemo{
public static void main(String[] args){
Box box = new Box(10,20,30); // this will call parametized constructor of class
}
}
Example - Stack Class
A Stack stores data using last-in and first-out ordering. To implement the Stack data structure has two operations - push and pop.
Push - To add an item on top of the stack.
Pop - To remove the top item from the stack.
public class Stack {
int stck[] = new int[10];
int top;
public Stack(){
top = -1;
}
public void push(int item){
if(top == 9){
System.out.println("Stack is full.");
}
else{
stck[++top] = item;
}
}
public int pop(){
if(top < 0){
System.out.println("Stack is empty");
return 0;
}
else{
return stck[top--];
}
}
}
public class StackTest {
Stack stack;
@BeforeTest
public void setup(){
stack = new Stack();
}
@Test
public void testLastElemInStack(){
stack.push(10);
stack.push(20);
stack.push(30);
Assert.assertEquals(stack. Pop(),30);
}
}