Unit 2
Unit 2
// fields
// constructor
this.myField = myField;
// methods
Creating Objects
Object is a basic unit of Object-Oriented Programming and represents the real
life entities.
Declaring object is also called instantiating a class.
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single class
may have any number of instances.
The general syntax for creating object is as follows:
Classname objectname; //declaration of object
Objectname = new classname (); //object instantiation
The above statement has three parts which is discussed in the detail below:
1. Declaration: The code set in the bold are all variable declarations that
associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the
object.
3. Initialization: The new operator is Followed by a call to a constructor,
which initializes the new object.
MyObject myObject;
// Create an object and assign its memory address to the reference variable
In this example, “MyObject” is the class of the object we want to create. We first
declare an object reference variable “myObject” of type “MyObject”. We then create
a new object of type “MyObject” suing the “new” keyword and assign its memory
address to “myObject”.
Methods are called using the object followed by the method name and any
required arguments in parentheses. If the method doesn't return a value, you
simply call it without assigning the result.
calculator.someMethod(); // Calling a method without a return value
Constructors, Characteristics of Constructors
Constructor:
A constructor initializes an object at the time of creation. It has the same name as the
class in which it resides. The constructor is automatically called when the object is
created, before the new operator completes. Constructors have no return type, not
even void. This is because the implicit return type of a class’ constructor is the class
type itself. It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object immediately.
There are three 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
Characteristics of Constructor:
1. A constructor has the same name as the class it belongs to.
2. A constructor has no return type, not even void.
3. A constructor is called automatically when an object is created using the
new keyword.
4. If a class does not have any constructors defined, the Java compiler
provides a default constructor with no arguments.
5. A class can have multiple constructors with different parameter lists.
This is called constructor overloading.
Types of constructors
There are four types of constructors in Java:
Default constructor: If not implemented any constructor by the
programmer in a class, Java compiler inserts a default constructor with
empty body into the code, this constructor is known as default constructor.
If user defines any parameterized constructor, then compiler will not create
default constructor and vice versa if user don’t define any constructor, the
compiler creates the default constructor by default during compilation.
no-arg constructor: Constructor with no arguments is known as no-arg
constructor. The signature is same as default constructor; however body
can have any code unlike default constructor where the body of the
constructor is empty.
Parameterized constructor: Constructor with arguments is known as no-
arg constructor. The signature is same as default constructor; however body
can have any code unlike default constructor where the body of the
constructor is empty.
Copy constructor: A constructor that initializes an object using another object of the
same class is known as a copy constructor. The copy constructor is used to create a
new object with the same values as an existing object.
this Keyword
“this” is a reference to object itself. ‘this’ keyword can be used to refer current
class instance variables, to invoke current class constructor, to return the
current class instance, as method parameter, to invoke current class method and
as an argument in the constructor call. “this” keyword when used in a
constructor can only be the first statement in Constructor and constructor can
have either this or super keyword but not both.
Example:
class A
{
int a=10;
public void show()
{
double a=100.200;
System.out.println(“Value of A is : “+a);
}
}
The above program code will display “Value of A is : 100.200”, because the
preference will always go to local variable or the variable with immediate
scope. System.out.println(“Value of A is : “+this.a); The above statement will
display “Value of A is: 10”, because the reference “this” will point to current
instance variable “a” of the class.
Finalize( ) Method
It is difficult for the programmer to forcefully execute the garbage collector to
destroy the object. But Java provides an alternative way to do the same. The
Java Object class provides the finalize() method that works the same as the
destructor. The syntax of the finalize() method is as follows:
Syntax:
protected void finalize throws Throwable()
{
//resources to be close
}
It is not a destructor but it provides extra security. It ensures the use of external
resources like closing the file, etc. before shutting down the program. We can
call it by using the method itself or invoking the method System.run
Finalizers OnExit(true).
o It is a protected method of the Object class that is defined in the
java.lang package.
o It can be called only once.
o We need to call the finalize() method explicitly if we want to override
the method.
o The gc() is a method of JVM executed by the Garbage Collector. It
invokes when the heap memory is full and requires more memory for
new arriving objects
o Except for the unchecked exceptions, the JVM ignores all the exceptions
that occur by the finalize() method.
Overloading methods
Method Overloading is a mechanism in which a class allows more than one
method with same name but with different prototype.
Multiple methods can be created by changing the no. of parameters, type of
parameters, order of parameters or combination of any.
The method binding is done by the compiler at compile time and fix the calling
method based on the actual parameter matching or by using implicit type
conversion.
This is also called as static binding, early binding or compile time
polymorphism.
Overloading constructors
Constructor Overloading:
Sometimes there is a need of initializing an object in different ways. This can
be done using constructor overloading.
E.g. A frame object can be created using default constructor or using title of the
frame.
Multiple constructors can be created by changing the no. of parameters, type of
parameters, order of parameters or combination of any.
Argument Passing
In Java, when you pass arguments to a method, they are transferred as copies
of the original values, and the method operates on these copies. Understanding
how arguments are passed in Java is crucial for understanding how methods
work. There are two types of argument passing in Java:
1) Pass by Value:
In Java, all arguments for primitive data types (such as `int`, `float`, `char`,
etc.) are passed by value. This means that a copy of the value is passed to the
method, and any changes made to the parameter inside the method do not
affect the original value.
1) Pass by Reference:
In Java, all objects (instances of classes) are passed by reference. This means
that when you pass an object to a method, you are passing a reference to the
same object in memory. Changes made to the object's state inside the method
are reflected in the original object.
Returning Objects
In Java, a method can return any type of data, including objects. When a
method returns an object, the return type of the method is the name of the class
to which the object belongs. Here’s an example of how to return an object from
a method in Java:
// method that returns an object
// more methods
In this example, MyClass is the class of the object we want to return. We first
define a constructor that takes an integer argument and sets the value of
myField. We then define a method called getMyObject() that returns a new
instance of MyClass with the same value of myField.
To use the returned object, you can create an object reference variable and
assign the result of the method call to it, like this:
MyClass myObject = new MyClass(42).getMyObject();
Recursion
Java supports recursion. Recursion is the process of defining something in terms of
itself. As it relates to Java programming, recursion is the attribute that allows a
method to call itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole number between 1 and N. For
example, 3 factorial is 1*2*3, or 6. Here is how a factorial can be computed by use of
recursive method:
Example:
Class Factorial{
Int fact(int n){
Int result;
If(n==1)
return 1;
result= fact(n-1)*n;
Return result;
}
}
Class Recursion {
Public static void main(String args[]) {
Factorial f= new Factorial();
System.out.println(“Factorial of 3 is” + f.fact(3));
System.out.println(“Factorial of 4 is” + f.fact(4));
System.out.println(“Factorial of 5 is” + f.fact(5));
}
}
Access control in Java is managed through the use of access modifiers. These
modifiers help to restrict the scope of a class, constructor, variable, method, or
data member. There are four types of access modifiers in Java:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: If you don’t specify any access level, it will be the default. The
access level of a default modifier is only within the package. It cannot be
accessed from outside the package.
3. Protected: The access level of a protected modifier is within the
package and outside the package through a child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package, and
outside the package.
Final Method:As earlier, we discussed the Final Keyword and How to declare the
Final Variable. We can declare Java methods as Final Method by adding the Final
keyword before the method name. The Method with Final Keyword cannot be
overridden in the subclasses. The purpose of the Final Method is to declare methods
of how’s definition can not be changed by a child or subclass that extends it.
Purpose of Final Methods:
Final methods are used to restrict the modification of a method's behavior
when a class is extended (subclassed).
Final methods prevent subclasses from changing the way a method works
when they override it.
By marking a method as final, you ensure that it always performs its
intended function, even in subclasses.
Marking methods as final helps maintain the integrity and consistency of method
behavior across subclasses.
Static Access
Final Access Modifier Modifier
Final access modifier does not allow Static access modifier allow the use of
the use of OOP concepts like OOP concepts within static blocks of
Inheritance and polymorphism. code.
6. **Regular Expressions**
- Advanced string matching with regex.
7. **Use Cases**
- Vital for text processing, user input, data handling.
8. **Best Practices**
- Opt for `StringBuilder` for efficient edits.
- Prefer `equals()` for comparisons.
9. **Summary**
- Java's string methods empower text handling in applications.