Unit – 6 Introducing Classes

By Haitomns G

Class:

A class defines the behavior of an object and is a template for multiple objects with similar features. Any class represented in a program is encapsulated in class. When application is written, class of objects are defined to create class some file. Class keywords, thus create an object, object, create template.

Class is a collection of fields of objects. A class is a book includes, as a template for the concept, each property is treated as an attribute of the class. For example, the book name, author name, number of pages it contains attributes.

Example:

                        Class Book {

                                    String name;

                                    String author_name;

                                    Int pages;

                        }

Object :

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc.

An object has three characteristics:

State: represents the data (value) of an object.

Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.

Creating an object

A class provides the blueprint for objects. So basically, an object is created from a class in the Java new keyboard is used to create new objects. There are 3 steps for creating objects from a class.

  1. Declaration
  2. Instantiation
  3. Initialization

Declaration

A variable declaration with a variable name with an object type.

Instantiation

The new keyword is used to create object.

Initialization

The new keyword initializes the new object.

Example:

            //Java Program to illustrate the use of Rectangle class which 

//has length and width data members 

class Rectangle{ 

 int length; 

 int width; 

 void insert(int l,int w){ 

  length=l; 

  width=w; 

 } 

 void calculateArea(){System.out.println(length*width);} 

class TestRectangle2{ 

 public static void main(String args[]){ 

  Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects 

  r1.insert(11,5); 

  r2.insert(3,15); 

  r1.calculateArea(); 

  r2.calculateArea(); 

}  

Assigning Object Reference Variables

 Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does?

Box b1 = new Box();

Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. This situation is depicted here:

image 4 2

 Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.  For example:

Box b1 = new Box();

Box b2 = new b1;

B1 = null;

Here, b1 has been set to null, but b2 still points to the original object.

Method:

A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again.

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.

image 4

Method in Java

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.

Calling a method in java;

To call a user-defined method, first, we create a method and then call it. A method must be created in the class with the name of the method, followed by parentheses (). The method definition consists of a method header and method body.

We can call a method by using the following:

method_name();  //non static method calling 

If the method is a static method, we use the following:

obj.method_name();   //static method calling 

Where obj is the object of the class.

In the following example, we have created two user-defined methods named showMessage() and displayMessage(). The showMessage() method is a static method and displayMessage() method is a non-static method.

Note that we have called the showMessage() method directly, without using the object. While the displayMessage() method is called by using the object of the class.

MethodCallExample.java

public class MethodCallExample 

//user-defined static method 

static void showMessage()  

System.out.println(“The static method invoked.”); 

//user-defined non-static method 

void displayMessage()  

System.out.println(“Non-static method invoked.”); 

public static void main(String[] args)  

//calling static method without using the object 

showMessage(); //called method 

//creating an object of the class 

MethodCallExample me=new MethodCallExample(); 

//calling non-static method 

me.displayMessage(); //called method 

Output:

The static method invoked.

Non-static method invoked.

Constructor in java

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Types of Java constructors

There are two types of constructors in Java:

  • Default constructor (no-arg constructor)
  • Parameterized constructor

Default Constructor:

Java Default Constructor

A constructor is called “Default Constructor” when it doesn’t have any parameter.

Syntax of default constructor:

<class_name>(){} 

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

//Java Program to create and call a default constructor 

class Bike1{ 

//creating a default constructor 

Bike1(){System.out.println(“Bike is created”);} 

//main method 

public static void main(String args[]){ 

//calling a default constructor 

Bike1 b=new Bike1(); 

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor. 

class Student4{ 

    int id; 

    String name; 

    //creating a parameterized constructor 

    Student4(int i,String n){ 

    id = i; 

    name = n; 

    } 

    //method to display the values 

    void display(){System.out.println(id+” “+name);}  

    public static void main(String args[]){ 

    //creating objects and passing values 

    Student4 s1 = new Student4(111,”Karan”); 

    Student4 s2 = new Student4(222,”Aryan”); 

    //calling method to display the values of object 

    s1.display(); 

    s2.display(); 

   } 

The this keyword in java

The this Keyword  Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword.   this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked.   You can use this anywhere a reference to an object of the current class’ type is permitted. To better understand what this refers to, consider the following version of Box( ).

Box (double w, double h, double d){

            this.width = w;

            this.height = h;

            this.depth – d;

}

This version of Box( ) operates exactly like the earlier version. The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking object. While it is redundant in this case, this is useful in other contexts, one of which is explained in the next section.

Instance Variable Hiding :

 As you know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. 

 Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables.

 However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor inside the Box class. If they had been, then width, for example, would have referred to the formal parameter, hiding the instance variable width. 

 While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any namespace collisions that might occur between instance variables and local variables. For example, here is another version of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name:

Box (double w, double h, double d){

            this.width = w;

            this.height = h;

            this.depth – d;

}

A word of caution: The use of this in such a context can sometimes be confusing, and some programmers are careful not to use local variables and formal parameter names that hide instance variables. Of course, other programmers believe the contrary—that it is a good convention to use the same names for clarity, and use this to overcome the instance variable hiding. It is a matter of taste which approach you adopt.

class Student {

    int rollno;

    String name;

    double fee;

    Student(int rollno, String name, double fee) {

        this.rollno = rollno;

        this.name = name;

        this.fee = fee;

    }

    void display() {

        System.out.println(rollno + ” ” + name + ” ” + fee);

    }

    public static void main(String args[]) {

        Student s1 = new Student(111, “Ankit”, 5000);

        Student s2 = new Student(112, “Sumit”, 6000);

        s1.display();

        s2.display();

    }

}

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.

It is automatically done by the garbage collector(a part of JVM) so we don’t need to make extra efforts.

Java Object finalize() Method

Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.

Syntax

protected void finalize() throws Throwable 

Throw

Throwable – the Exception is raised by this method

Example 1

public class JavafinalizeExample1 { 

     public static void main(String[] args)  

    {  

        JavafinalizeExample1 obj = new JavafinalizeExample1();  

        System.out.println(obj.hashCode());  

        obj = null;  

        // calling garbage collector   

        System.gc();  

        System.out.println(“end of garbage collection”);  

    }  

    @Override 

    protected void finalize()  

    {  

        System.out.println(“finalize method called”);  

    }  

Java Stack

The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection of objects. One of them is the Stack class that provides different operations such as push, pop, search, etc.

In this section, we will discuss the Java Stack class, its methods, and implement the stack data structure in a Java program. But before moving to the Java Stack class have a quick view of how the stack works.

The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and pop operation removes an element from the top of the stack. Let’s see how they work on stack.

Apart from the methods inherited from its parent class Vector, Stack defines the following methods −

image 5

Example:

import java.util.*;

public class StackDemo {

   static void showpush(Stack st, int a) {

      st.push(new Integer(a));

      System.out.println(“push(” + a + “)”);

      System.out.println(“stack: ” + st);

   }

   static void showpop(Stack st) {

      System.out.print(“pop -> “);

      Integer a = (Integer) st.pop();

      System.out.println(a);

      System.out.println(“stack: ” + st);

   }

   public static void main(String args[]) {

      Stack st = new Stack();

      System.out.println(“stack: ” + st);

      showpush(st, 42);

      showpush(st, 66);

      showpush(st, 99);

      showpop(st);

      showpop(st);

      showpop(st);

      try {

         showpop(st);

      } catch (EmptyStackException e) {

         System.out.println(“empty stack”);

      }

   }

}

Also, Read

  1. Unit-1 Java’s Lineage
  2. Unit-3 Data types, Variables, and Array
  3. Unit-4 Operator
  4. Unit: 5 Control Statements

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

Leave a Comment

Slide to prove you're not a bot/spammer *