Wednesday, 3 January 2024

Unit2 : Introducing classes, object and method | Java Programming | ICT. Ed 455 | BICTE | Fifth Semester | Bicte blog

 

Unit2 : 

Introducing classes, object and method

2.1 class fundamentals

2.2 object creation

2.3 methods

2.4 command line arguments

2.5 constructors

2.6 Garbage collection

2.7 This keyword

2.8 static field and methods

2.9 nested and inner classes

2.10 variable length argumnets

 

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

Syntax to declare a class:

  1. class <class_name>{  
  2.     field;  
  3.     method;  
  4. }  

What is an object in Java


An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.

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.

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

  • An object is a real-world entity.
  • An object is a runtime entity.
  • The object is an entity which has state and behavior.
  • The object is an instance of a class.

Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.


Advantage of Method

  • Code Reusability
  • Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

  1. //Java Program to illustrate how to define a class and fields  
  2. //Defining a Student class.  
  3. class Student{  
  4.  //defining fields  
  5.  int id;//field or data member or instance variable  
  6.  String name;  
  7.  //creating main method inside the Student class  
  8.  public static void main(String args[]){  
  9.   //Creating an object or instance  
  10.   Student s1=new Student();//creating an object of Student  
  11.   //Printing values of the object  
  12.   System.out.println(s1.id);//accessing member through reference variable  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:

0 
null

 

Java Command Line Arguments

The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an input.

So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.

  1. class CommandLineExample{  
  2. public static void main(String args[]){  
  3. System.out.println("Your first argument is: "+args[0]);  
  4. }  
  5. }  
  1. compile by > javac CommandLineExample.java  
  2. run by > java CommandLineExample sonoo  

Constructors 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.

Rules for creating Java constructor

There are two rules defined for the constructor.

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

  1. <class_name>(){}  

Example of default constructor

  1. //Java Program to create and call a default constructor  
  2. class Bike1{  
  3. //creating a default constructor  
  4. Bike1(){System.out.println("Bike is created");}  
  5. //main method  
  6. public static void main(String args[]){  
  7. //calling a default constructor  
  8. Bike1 b=new Bike1();  
  9. }  
  10. }  
Bike is created

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values

  1. //Let us see another example of default constructor  
  2. //which displays the default values  
  3. class Student3{  
  4. int id;  
  5. String name;  
  6. //method to display the value of id and name  
  7. void display(){System.out.println(id+" "+name);}  
  8.   
  9. public static void main(String args[]){  
  10. //creating objects  
  11. Student3 s1=new Student3();  
  12. Student3 s2=new Student3();  
  13. //displaying values of the object  
  14. s1.display();  
  15. s2.display();  
  16. }  
  17. }  

Output:

0 null
0 null

Java Parameterized Constructor

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

Why use the 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.

  1. //Java Program to demonstrate the use of the parameterized constructor.  
  2. class Student4{  
  3.     int id;  
  4.     String name;  
  5.     //creating a parameterized constructor  
  6.     Student4(int i,String n){  
  7.     id = i;  
  8.     name = n;  
  9.     }  
  10.     //method to display the values  
  11.     void display(){System.out.println(id+" "+name);}  
  12.    
  13.     public static void main(String args[]){  
  14.     //creating objects and passing values  
  15.     Student4 s1 = new Student4(111,"Karan");  
  16.     Student4 s2 = new Student4(222,"Aryan");  
  17.     //calling method to display the values of object  
  18.     s1.display();  
  19.     s2.display();  
  20.    }  
  21. }  

Output:

111 Karan
222 Aryan

 

This keyword in java:

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object.




Usage of Java this keyword

Here is given the 6 usage of java this keyword.

  1. this can be used to refer current class instance variable.
  2. this can be used to invoke current class method (implicitly)
  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 to return the current class instance from the method.

this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

  1. class Student{  
  2. int rollno;  
  3. String name;  
  4. float fee;  
  5. Student(int rollno,String name,float fee){  
  6. this.rollno=rollno;  
  7. this.name=name;  
  8. this.fee=fee;  
  9. }  
  10. void display(){System.out.println(rollno+" "+name+" "+fee);}  
  11. }  
  12.   
  13. class TestThis2{  
  14. public static void main(String args[]){  
  15. Student s1=new Student(111,"ankit",5000f);  
  16. Student s2=new Student(112,"sumit",6000f);  
  17. s1.display();  
  18. s2.display();  
  19. }}  

Output:

111 ankit 5000.0

112 sumit 6000.0

Java static keyword:

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

The static can be:

  1. Variable (also known as a class variable)
  2. Method (also known as a class method)
  3. Block
  4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.

  • The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
  • The static variable gets memory only once in the class area at the time of class loading.

It makes your program memory efficient (i.e., it saves memory).

Example of static variable

  1. //Java Program to demonstrate the use of static variable  
  2. class Student{  
  3.    int rollno;//instance variable  
  4.    String name;  
  5.    static String college ="ITS";//static variable  
  6.    //constructor  
  7.    Student(int r, String n){  
  8.    rollno = r;  
  9.    name = n;  
  10.    }  
  11.    //method to display the values  
  12.    void display (){System.out.println(rollno+" "+name+" "+college);}  
  13. }  
  14. //Test class to show the values of objects  
  15. public class TestStaticVariable1{  
  16.  public static void main(String args[]){  
  17.  Student s1 = new Student(111,"Karan");  
  18.  Student s2 = new Student(222,"Aryan");  
  19.  //we can change the college of all objects by the single line of code  
  20.  //Student.college="BBDIT";  
  21.  s1.display();  
  22.  s2.display();  
  23.  }  
  24. }  

Output:

111 Karan ITS
222 Aryan ITS
 

Java Inner Classes (Nested Classes)

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.

Additionally, it can access all the members of the outer class, including private data members and methods.

Syntax of Inner class

  1. class Java_Outer_class{  
  2.  //code  
  3.  class Java_Inner_class{  
  4.   //code  
  5.  }  
  6. }  

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:

  1. Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
  2. Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
  3. Code Optimization: It requires less code to write.

Inner Class Example

TestMemberOuter1.java

  1. class TestMemberOuter1{  
  2.  private int data=30;  
  3.  class Inner{  
  4.   void msg(){System.out.println("data is "+data);}  
  5.  }  
  6.  public static void main(String args[]){  
  7.   TestMemberOuter1 obj=new TestMemberOuter1();  
  8.   TestMemberOuter1.Inner in=obj.new Inner();  
  9.   in.msg();  
  10.  }  
  11. }  

Output:

data is 30
 
 
 

Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.

We don't have to provide overloaded methods so less code.

Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

  1. return_type method_name(data_type... variableName){}  

 

Simple Example of Varargs in java:

  1.     
  2. class VarargsExample1{  
  3.    
  4.  static void display(String... values){  
  5.   System.out.println("display method invoked ");  
  6.  }  
  7.   
  8.  public static void main(String args[]){  
  9.   
  10.  display();//zero argument   
  11.  display("my","name","is","varargs");//four arguments  
  12.  }   
  13. }  
  14.       
Output:display method invoked
       display method invoked


No comments:

Post a Comment

Teaching Method in ICT Education | Syllabus | Seven Semester | BICTE

  Course Title: Teaching Method in ICT Education Course No.: ICT. Ed. 478                                            Nature of ...