Professional Documents
Culture Documents
Java Programming Class and Objects
Java Programming Class and Objects
Java Programming Class and Objects
UNIT-2
Classes and objects
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:
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:
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
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:
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:
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.
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.
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]
Output:
Passing and Returning Arrays in Methods:
Output:
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
Output:
Output:
Program to demonstrate Anonymous Inner Class:
Output:
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.