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
//Java Program to create and call a default constructor
1. class Bike1{
2. //creating a default constructor
3. Bike1(){System.out.println("Bike is created");}
4. //main method
5. public static void main(String args[]){
6. //calling a default constructor
7. Bike1 b=new Bike1();
8. }
9. }
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
//Let us see another example of default constructor
//which displays the default values
1. class Student3{
2. int id;
3. String name;
4. //method to display the value of id and name
5. void display(){System.out.println(id+" "+name);}
6. public static void main(String args[]){
7. //creating objects
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. //displaying values of the object
11. s1.display();
12. s2.display();
13. }
14. }
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. class TestThis2{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
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
//Java Program to demonstrate the use of static variable
1. class Student{
2. int rollno;//instance variable
3. String name;
4. static String college ="ITS";//static variable
5. //constructor
6. Student(int r, String n){
7. rollno = r;
8. name = n;
9. }
10. //method to display the values
11. void display (){System.out.println(rollno+" "+name+" "+college);}
12. }
13. //Test class to show the values of objects
14. public class TestStaticVariable1{
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(222,"Aryan");
18. //we can change the college of all objects by the single line of code
19. //Student.college="BBDIT";
20. s1.display();
21. s2.display();
22. }
23. }
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
class Java_Outer_class{
//code
1. class Java_Inner_class{
2. //code
3. }
4. }
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 multiple 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. class VarargsExample1{
2. static void display(String... values){
3. System.out.println("display method invoked ");
4. }
5. public static void main(String args[]){
6. display();//zero argument
7. display("my","name","is","varargs");//four arguments
8. }
9. }
Output: display method invoked display method invoked