Java Programming Class and Objects

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Java Programming

UNIT-2
Classes and objects

Topics covered in this unit:


• class declaration,
• creating objects,
• methods,
• constructors and constructor overloading,
• garbage collector,
• importance of static keyword and examples,
• this keyword,
• arrays,
• command line arguments,
• nested classes.
Classes and Objects:
• A class is a blueprint or prototype that defines the variables and methods common to all objects
of a certain kind.
• Class can be thought of as a user defined data type and an object as a variable of that data type,
which can contain data and methods i.e. functions, working on that data.
• All object instances have their own copies of instance variable.
• Each object has its own copy of instance variables which is different from other objects created
out of the same class.
Defining a Class:
• A class is declared using class keyword followed by the name of the class.
Syntax:
[modifiers] class <class-name> {
// instance data variables
// class ( static ) data variables
// instance methods
// static methods
}
Example:
Objects:
• The real-world objects have state and behavior.
• For example,
– horses have state (name, color, breed, hungry) and horses have behavior (barking,
fetching, and slobbering on your newly cleaned slacks).
– Bikes have state (gear, accelerator, two wheels, number of gears, brakes) and behavior
(braking, accelerating, slowing down and changing gears).
• An object is a software bundle which encapsulates variables and methods, operating on those
variables.
Declaring and creating an Object:
• Object declarations is same as variable declarations for e.g.
<class name > <object var> = new <Constructor>(Param list)
• Ex:
Box b = new Box(12, 7,9);
• A normal variable holds a single type of literal, while an object is a instance of a class with a set
of instance variables and methods which performs certain task depending what methods have
been defined for.
The mechanism involved in creating the Object
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name with an object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
Step 1:
Box b;

Effect: b  null

Declares the class variable. Here the class variable contains the value null. An attempt to access the
object at this point will lead to Compile-Time error.
Step 2:
Box b=new Box();

Here new is the keyword used to create the object. The object name is b. The new operator allocates
the memory for the object, that means for all instance variable inside the object, memory is allocated.

Width
Height
Effect: b Depth

Box Object

Step 3:
There are many ways to initialize the object. The object contains the instance variable. The
variable can be assigned values with reference of the object.
b.width=12.34;
b.height=3.4;
b.depth=4.5;

Example:

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.
Instead, after this fragment executes, b1 and b2 will both refer to the same object.

Difference between objects and class:


• Objects are software bundles, resembles real world entities.
• Objects perform some actions to continue the execution of process.
• With-out creating objects we cannot do any activity.
• The class defines the properties and behavior of the object.
• The instance variables define the properties of the object.
• Each object contains separate copy of instance variables.
• Each object maintains state (all values stored in the instance variables) at particular point of
time.
• All objects of same class shares the methods of the class defined within the class.
Method:
• Method is a function which represents to perform a task and the method is a function called
through object.
• A class contains collection of methods.
• Those methods define the behavior of the object.
• Definition of the method is written in the class definition.
• Methods are two types:
• Instance method : this type method is called only through object, so we need to create
an object to call the method.
• Static method : this type method is called through the class name, so there is no need
create object.
• Methods are used in message passing, t communicate among objects.
• Methods are useful for a) to make reusable, b) task wise modularization to reduce complexity.
Syntax for a method declaration:
• [modifiers] return_type method_name (parameter_list) [throws_clause]
{
[statement_list]
}
Ex:
public static double compute(double x, double y) throws ArithmeticException
{
return (x / y);
}
Elements of a method:
• Return Type:
– can be either void or if a value is returned, it can be either a primitive type or a class.
– If the method declares a return type, then before it exits it must have a return statement.
• Method Name:
– The method name must be a valid Java identifier, as discussed in chapter 3.
• Parameter List:
– Contains zero or more type/identifier pairs make up the parameter list.
– Each parameter in parameter list is separated by a comma.
• Throws clause:
– A list of unhandled exceptions separated by comma.
• Curly Braces:
– The method body is contained in a set of curly braces (opening ‘{‘ and closing ‘}’).
Defining methods in a class:

Method Invocation:
• Methods cannot run on their own, they need to be invoked by the objects they are a part of.
• The methods can also return values from themselves if they wish to.
• Data that are passed to a method are known as arguments or parameters;
– Formal Parameters: the identifier used in a method to stand for the value that is passed
into the method by a caller
– Actual Parameters: The actual value that is passed into the method by a caller
• The number and type of the actual and formal parameters should be same for a method.
• In Java, the parameters are passed by value for primitive data types, and passed by reference
for objects and arrays.
Calling methods through objects:
Output:

Optional Modifiers Used with Methods:

Method Vs Function:
• A method is a member function of a class, where a function is not the member of a class.
• A method is called by an object reference, but a function is called directly.
• A method is able to access data of the object, which is associated in the method call.
• A method may have different implementations, and the proper implementation is selected to
execute at the time of method execution.

Method Overloading:
• Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different.
• It allows different methods to have same name, but different signatures where signature can
differ by number of input parameters or type of input parameters or both.
• Overloading is related to compile time (or static) polymorphism.
• Advantage of method overloading is it increases the readability of the program and also
increases comfort to the users (callers of the method ).
• We don’t have to create and remember different names for functions doing the same thing.
• We cannot overload by return type.
• We can demonstrate the advantage of method overloading with two classes in java.
Example:
Java.util.Scanner : class contains non-overloaded methods
Java.io.PrintStream : class contains overloaded methods

Three ways to overload a method:


• In a class, there can be several methods sharing the same name but differ in a) Parameter types,
b) Number of parameters d) Order of the parameters declared in the method
• By depending on the parameters provided for the method, in the run time, compiler determines
which version of the method to execute.
• An overloaded method may or may not have different return types. But return type alone is not
sufficient for the compiler to determine which method is to be executed at run time.
Example:

Java program to demonstrate method overloading:


Calling the overloaded methods:

Output:
Constructor:
• Java has a mechanism, known as constructor, for automatically initializing the values for an
object, as soon as the object is created.
• Constructors have the same name as the class it resides in and is syntactically similar to a
method.
• It is automatically called immediately after the object for the class is created by new operator.
• Contractors have no return type, not even void, as the implicit return type of a class’ constructor
is the class type itself.
• Types of Constructors:
– Default Constructor:
• Implicit Default Constructor
• Explicit Default Constructor
– Parameterized Constructor
No-argument constructor or Default Constructor:
• A constructor that has no parameter is known as default constructor.
• If we don’t define a constructor in a class, then compiler creates default constructor (with no
arguments) for the class, which is known as implicit default constructor.
• And if we write at least one constructor (with arguments or no-argument ) in the class
definition, then compiler does not create default constructor.
• Default constructor provides the default values to the object like 0, null etc. to the data
members, depending on the type.

Output:
Explicit default constructor:

We can also include a parameter-less constructor in class definitions, also known as explicit
default constructor. Explicit default constructor is used to create generalized objects; each object
contains same values to its data members.

Output:

Parameterized constructors:

• A constructor that has parameters is known as parameterized constructor.


• If we want to initialize fields of the class with your own values, then we use parameterized
constructor.
• Parameterized constructor is more useful, to provide proper initial state to the object,
particularly when the data members are private.
• We can use setter methods to modify the values to data members individually later.
Output:

Constructor Vs Methods:
Constructor Overloading:
• Constructors for a class have the same name as the class but they can have different signature
i.e. different types of arguments or different number of arguments.
• Such constructors can be termed as overloaded constructors.
• Different constructors are used to create objects with different set of values.
• It also comes under compile time (static) polymorphism.
Program to demonstrate Constructor overloading:

Calling overloaded constructors:

Output:
Garbage Collector:
• In Java many objects are created as required, they should be deleted from memory after their
usage.
• The Java runtime environment deletes objects when it determines that they are no longer
required( identified as out of scope )
• Garbage Collection is process, which is a way to destroy the unused objects.
• To remove unused objects, we were using free() function in C language and delete() in C++.
• But in java, garbage Collection is performed automatically. so the programmer don't need to
make extra efforts.
• It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
• An object can be unreferenced, because
– a) By nulling the reference, b) By assigning a reference to another c) By anonymous
object etc.
How can an object be unreferenced?

finalize() method:
• Sometime an object will need to perform some specific task before it is destroyed such as
closing an open connection or releasing any resources held.
• To handle such situation finalize() method is used.
• finalize() method is called by garbage collection thread before collecting object.
• Its the last chance for any object to perform cleanup utility.
• finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
• finalize() method is declare as proctected inside Object class.
gc() Method:
• gc() method is used to call garbage collector explicitly.
• However gc() method does not guarantee that JVM will perform the garbage collection.
• It only request the JVM for garbage collection.
• This method is present in System class or Runtime class.

Program to demonstrate finalize() method and System.gc() methods:

Output:

static keyword:
• Sometimes we would like to have multiple objects, to share variables or methods.
• The static keyword effectively does this for us.
• Static keyword can be applied to variables/methods and blocks of code.
• Java supports three types of variables: Local, Instance and Class variables
– Local variables are declared inside a method, constructor, or a block of code
– Instance variable are declared inside a class, but outside a method
– Class/static variables declaration is preceded with a static keyword. They are also
declared inside a class, but outside a method.
• The most important point about static variables is that there exists only one a single copy of
static variables per class.
static methods:
• Like static variables, we do not need to create an object to call our static method. Simply using
the class name will sufficient.
• Static methods however can only access static variables directly.
• But Instance variables cannot be accessed by the static method directly.
• To make a method static, we simply precede the method declaration with the static keyword.
static initialization block:
• A block of statements with static keyword applied to it.
• This block is used for initializing static or class variables.
• In case, some logic is used for assigning values to the static variables, static blocks can be used.
• The syntax for static block is as follows:
static {
// code for initialize static data members
}
Program to demonstrate static keyword:

Output:
this keyword:
• ‘this’ is a keyword in Java which is used as a reference to the object of the current class, with in
an instance method or a constructor.
• Using this you can refer the members of a class such as constructors, variables and methods.
• Note: The keyword this is used only within instance methods or constructors.
• In general, the keyword this is used to :
– Differentiate the instance variables from local variables if they have same names, within
a constructor or a method.
– Call one type of constructor from other constructor in a class, also known as constructor
chaining.
– To return the current object by the invoked method.

Program to demonstrate this keyword:

Output:
Arrays:
• Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type.
• Declaring Array Variables:
– dataType[] arrayRefVar;
or
– <dataType> arrayRefVar[];
• Ex :
• int[] marks; or int marks[];
• In java, arrays are also objects. The syntax to create array objects :
– arrayRefVar = new <dataType>[arraySize];
• Ex:
• marks = new int[10];
• Declaring an array variable, and creating array object in a single statement:
– dataType[] arrayRefVar = new dataType[arraySize];
– Ex:
– int[] marks = new int[10];
• Each array is associated with a member: length represents size of the array.
Initialization of array elements:
• Dynamically initialized array object:
int[] marks = { 56,67,59,87,48, 36,77,62, 91, 80 };
• Initializing array elements using for loop :

Output:
Two dimensional arrays:
• In java two dimensional arrays are treated as array of arrays.
• It means each row is an array of one dimension.
• Example :
declaring a 3 X 4 two-D array
int[][] b; // declaration of 2D array
creating array object
b = new int[ 3 ][ 4 ]; //creating array
• Syntax for declaring and creating a 2-D array :
datatype[][] arrayname = new datatype[rows][cols]

We can explain a two dimensional array as below:

Program to demonstrate a 2-D array:


Output:

Ragged or Jagged Array:


• an array with rows of non-uniform length is known as a Ragged array.

Program to demonstrate a Ragged array:

Output:
Passing and Returning Arrays in Methods:

Output:

Variable arguments in methods:


• Variable arguments can be used when the number of arguments that you want to pass to a
method are not fixed.
• The method can accept different number of arguments of same type whenever they are called.
Output:

Command Line Arguments:


• Sometimes you will want to pass some information into a program when you run it.
• This is accomplished by passing command-line arguments to main( ).
• main() method in java has only one parameter, that is an array of strings.
• The command line arguments are stored as strings in the String array passed to main( ).
• The number of command line arguments can be obtained from the length property of the array.
• We can pass the command line arguments as strings only.

Program to demonstrate command line arguments:

Output:
Nested classes:
• A nested class is one that is declared entirely in the body of another class or interface.
• The class, which is nested, can only exist as long as the enveloping class exists.
• So, the scope of nested class is limited to the scope of enveloping class.
• Types of nested classes:
• Static nested class
• Non static nested class( Inner class)
• Local class
• Anonymous class

Points regarding Non static nested class (Inner class):


• The inner class has access to all members of the enveloping class including protected and
private members.
• The enveloping class does not have direct access to nested class members. It is only through the
reference of inner class.
• An instance of inner class outside the enveloping class can only be created with an instance of
outer class.
• A method of inner class cannot be directly accessed by the object of outer class. The access is
through the object of inner class by a fully qualified name for accessing.

Advantages of nested classes:


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

Types of Nested classes:


• Non-static inner class:
– A non-static class that is created inside a class but outside a method is called member
inner class.
– It has access to all members of the enveloping class including protected and private
members.
– An instance of inner class outside the enveloping class can only be created with an
instance of outer class.
• Static inner class:
– A static class i.e. created inside a class is called static nested class in java.
– It cannot access non-static data members and methods. It can be accessed by outer
class name.
– An inner class written inside the interface is automatically treated as static inner class.
• Local class:
– A class i.e. created inside a method is called local inner class in java.
– If you want to invoke the methods of local inner class, you must instantiate this class
inside the method.
• Anonymous Inner class:
– A class have no name is known as anonymous inner class.
– It should be used if you have to override method of class or interface.
– Java Anonymous inner class can be created by two ways:
• Class (may be abstract or concrete).
• Interface

Program to demonstrate Non-Static inner class:

Output:

Program to demonstrate Static Inner Class:


Output:

Difference between Non-static inner class and static inner class:

Non-static Inner class Static Inner class


To create object of non-static inner class, Object of Static inner class can be created even
before that we should create outer class object. without creating outer class object.
We cannot declare static members in non-static Inside static nested class, we can declare static
inner class members.
We cannot declare main() method in non-static We can declare main() method in static inner
inner class. class, and we can execute it directly from the
command prompt.
Inside the non-static inner class, we can access From static nested class, we can access only static
both static and non static members of outer members of outer class directly.
class directly.

Program to demonstrate Local Class:

Output:
Program to demonstrate Anonymous Inner Class:

Output:

Difference between Top level class and anonymous inner class:

Top level class Anonymous Inner class


Can extend only one class at a time. Can extend only one class at a time.
Can implement any no. of interfaces at a time. Can implement only one interface at a time.
Can extend a class and also can implement Can extend a class or can implement interface,
interface simultaneously. but not both simultaneously.
We can write constructor because we know the We cannot write constructor because anonymous
name of the class. inner class not having any name.
List of questions asked in the previous question papers:

Part-A
a) Define class and object in java
b) Discuss about inner classes.
c) How constant are declared to java? Explain.
d) Explain about the this keyword with examples.
e) List the various ways of ‘static’ keyword usage.
f) Write about garbage collection
g) Illustrate the usage of ‘this’ keyword.
h) Explain about the static keyword with examples.
i) What is an Object? How to allocate memory for objects?
j) List out the characteristics of the static method.
k) What is a constructor? When does the compiler supply default constructor for a class?
l) Differentiate between array and vector with examples.

Part-B
1. a) How to share the data among the functions with the help of static keyword? Give example.
b) Write and explain the syntax of constructor with example
2. a) How to assign the values to the variables in the class at the time of creation of object to that class?
Explain with example.
b) How garbage collector plays its role? Explain.
3. a) What is an array? How arrays are declared and initialized? Explain with examples. (8M)
b) Write a java program to check the given string is a palindrome or not.
4. a) Illustrate constructor overloading.
b) With a program illustrate the use of command line arguments.
5. a) What is a constructor? What is its requirement in programming? Explain with program.
b) How to create objects? Does Java support object destruction? Justify your answer. (8M)
6. a) Write a Java program to find the sum of the squares of the diagonal elements of a square matrix.
b) Write a Java program to sort a given set of strings in the alphabetical order where the strings are
supplied through the command line.
7. a) What do you mean by static class and static method? Explain with example.
b) Write a java program to illustrate "Constructor Overloading".
8. a) Write a program to perform the following functions using classes, objects, constructors and
destructors wherever necessary
i) Read 5 subjects marks of 5 students
ii) Calculate the total and print the result on the screen
b) Explain clearly about how Java handles cleaning up of unused objects.
9. a) Why do constructors does not have any return type? Explain it with proper example.
b) With an example program explain the overloading methods and constructors.
10. a) How to overload methods in Java? Explain the concept of ‘Using objects as parameters to
methods.
b) Explain the following i) Access Control ii) “this” Key word
Java Programming - Assignment -2

Part-A
a) How garbage collector plays its role? Explain.
b) What is an Object? How to allocate memory for objects?
c) List out the characteristics of the static method.
d) What is a constructor? When does the compiler supply default constructor for a class?
e) Differentiate between array and vector with examples.

Part-B
1. a) How to share the data among the functions with the help of static keyword? Give example.
b) Discuss about inner classes.
2. a) What is an array? How arrays are declared and initialized? Explain with examples.
b) What is a constructor? What is its requirement in programming? Explain with program.
3. a) What do you mean by static class and static method? Explain with example.
b) Why do constructors does not have any return type? Explain it with proper example.
4. a) How to overload methods in Java? Explain the concept of ‘Using objects as parameters to methods.
b) Explain “this” Key word with good example.

Programs:
1) Write a program to perform the following functions using classes, objects, constructors and
destructors wherever necessary
i) Read 5 subject's marks of 5 students
ii) Calculate the total and print the result on the screen
2) Write a java program to illustrate "Constructor Overloading".
3) With a program illustrate the use of command line arguments.

You might also like