CH 2 Class, Objects and Methods
CH 2 Class, Objects and Methods
CH 2 Class, Objects and Methods
1. Class and object:- classes and objects in java are the fundamental components of
OOP’s
which revolve around the real life entities.
- Everything in java is associated with classes and objects, along with its attribute and
methods.
-Classes creates objects and objects use methods to communicate between them.
-java supports some OOP’s concepts: polymorphism, Inheritance,
Encapsulation,Abstraction,Classes,Objects,Instance,Method, Message Passing.
• Recursion: The process in which a function call itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
• Ex: we compute factorial n if we know factorial of (n-1) . The base case for factorial would be n=0. we
return 1, when n=0;
program Factorial.java
• Passing Objects as Arguments to methods: we can pass object like any other variable as
argument to a method in java . Object in java are reference variables, so for objects a
value which is the reference to the object is passed . Objects are implicitly passed by
use of call-by-reference.
• Program Student.java
Returning object from method: When a method returns an object, the return type of the method is the name of the class to which the
object belongs and the normal return statement in the method is used to return the object.
Prog :
Class Time
{
Private int hr, mn, sec;
Time() //constructor
{
hr = mn =sec =0;
}
Time(int hh, int m , int ss) // constructor with 3 parameters
{
hr=hh;
mn= m;
sec =ss;
}
Time add(time t2)
{
Time Temp = new Time();
New Operator ,this and static keyword, finalize() method:-
-New Operator: 1) To create an object of the class: the ‘new’ operator in java is
responsible for the creation of new object.
The dynamically allocation just means that the memory is allocated at the run time of
the program.
a) Declaration:- A variable declaration with a variable name with an object type.
b) Instantiation:- the ‘new’ keyword is used to create the object.
c) Initialization:- the ‘new’ keyword is followed by a call constructor .This call initialization
the new object.
Ex: Student ob = new Student();
2) To create anonymous object to assign expression:- the reference returned by the new
operator does not have to be assigned to a class variable .It can also be used directly in an
expression.
Ex: double height = new Box().height;
3) To instantiate an array: ‘new’ operator is also used to create an array .
Ex: int arr[] =new int[5];
• this keyword:- this keyword in java is a reference variable that refers to the current
object of a method or a constructor.
Following are various uses of ‘this’ keyword in java:
i. It can be used to refer instance current variable of current class.
ii. It can be used to invoke or initiate current class constructor.
iii. It can be passed as an argument in the method call.
iv. It can be passed as argument in the constructor call.
v. It can be used to return the current class instance.
1. To refer current class instance variable: 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.
Program: ThisDemo.java
2. To invoke current class constructor: this() constructor call can be used to invoke the current class
constructor . The this() constructor call should be used to reuse the constructor from the constructor .
Program: ThisExample.java
• Static Keyword:- in java is used for memory management mainly .We can apply static keyword with
variables ,methods, blocks and nested classes .
-The static can be: i) Field ii) Method iii) Block
i) Static field: the variable which have been declared in the class.
-When a variable is declared as static, then a single copy of the variable is created and divided among all
objects at the class level. static variables are essentially global variables .
-All the instance of the class share the same static variable ,Static variables can be created at the class level only.
-when a member is declared static, it can be accessed before any object of its class is created and without
reference to any object.
-program.
ii) Static Method:- When a method is declared with the static keyword, it is known as a
static method .
-the most common example of a static method is the main() method.
-method declared as static can have the following restrictions:
a. They can directly call other static method only.
b. They can access static data directly.
c. The static methods of a particular class can only access the static variables and can
change them.
d. A static method can only call other static method.
e. Static methods can’t refer to non-static variables or methods.
f. Static methods can refers to “super” or “this” members as there is no object .
g. Syntax ClassName.MethodName();
h. Prog StaticDemo1.java
iii) Static Block: The static block is a block of statements inside a java class that will be executed when a class is first loaded
into the JVM.
-the static block gets executed only once by JVM when the class is loaded into the memory by java class loader.
-A static block helps to initialize the static data members . It is executed before the main method at the time of class loading.
Syntax: static
{
//program code
}
Ex: class StaticBlock
{
static int x;
static int y;
Static
{
X=10; y=20;
System.out.println(“Inside static block”);
}
Public Static void main(String args[])
{
System.out.println(“Inside main() method”);
System.out.println(“x= “ + x + “\t” + “y =“+y);
}
}
• main() method is static in java:-
- Java main() method is always static, so that compiler can call it without the creation of
an object or before the creation of an object of the class.
a. In any java program , the main() method is the starting point from where compiler
starts program execution , so the compiler needs to call the main() method.
b. if the main() is allowed to be non-static , then while calling the main() method JVM
has to initiate its class.
c. it has to call the constructor of that class.
d. The main() method in java must be declared public, static and void
• Finalize() method:- The finalize() is called by the garbage collector on an object when garbage
collection determines that there are no more references to the object .
- It is defined in java.lang. Object
- Garbage collection is a mechanism to remove object from the memory when they are no longer need.
- Garbage collection is carried out by the garbage collector.
- Garbage collector keeps track of how many references an object has.
- It releases the memory by destroying the object when it has no longer any references.
- Garbage collector performs clean up activity. Cleanup activity means closing the resources associated
with that object like database connection ,network connection or we can say resource deallocation .
- Once the finalize method completes immediately garbage collector destroys that object.
- Garbage collector invokes the finalize method.
- This method is called by garbage collector just before they destroy the object from memory.
- Declaration:-
protected void finalize()
{
//code
}
• Nested class, Inner class and Anonymous inner class:-
Nested Classes:- In java, we can define a class inside another class, that class is known as java nested
class.
-The class which contains the other class is known as the outer class and the and the contained class is
known as inner class.
-Nested classes are divided into two types:-
i. Non-static nested classes:-these are the non-static members of a class.
ii. Static nested classes:- these are the static members of a class.
Nested Classes: 1)Inner classes 2) Static nested classes
1)Inner classes- i) Inner classes ii)Method local inner classes iii)Anonymous inner classes
A] Inner classes (non-static nested classes):- In java , it is also possible to nest classes(a class within a
class) .The purpose of nested classes is to group classes that belongs to each other,
-It can access all the members of the outer class, including private data members and methods.
-Inner classes are a security mechanism in java, generally a class cannot be associated with the access
modifier private, but if we have the class as a member of other class, then the inner class can be made
private and this is also used to access the private members of a class.
• Points about inner classes:- i. These are non-static nested classes.
ii. They can have all types of access modifier in their declaration.
iii. Just like instance variable and methods , inner classes are associated with an instance of
the enclosing class.
iv. They have access to all members of the enclosing class, regardless of whether they are
static or non-static.
-Inner classes are of 3 types depending on how and where you define them: they are:
i. Inner class
ii. Method local inner class
iii. Anonymous inner class
i. Inner class: Creating an inner is quite simple .you just need to write a class within a class.
-Unlike a class , an inner class can be private and once you declare an inner class private ,it
cannot be accessed from an object outside the class.
Syntax: class java_Outer_class
{
//code
Class java_Inner_class
{
//code
}
}
-Advantages of java inner classes:-
a.Nested classes represent a particular type of relationship, that is it can access all the
members(data members and methods) of the outer class, include private.
b. Nested classes are used to develop more readable and maintainable code because it
logically groups classes and interfaces in one places only.
c. It requires less code to write.
Ex: class Outer
{
int num;
private class Inner //inner class defined
{
public void print()
{
System.out.println(“This is an inner class”);
}
}
//Accessing the inner class from the method within
Void displayInner()
{
Inner inner= new Inner();
Inner.print();
}
}
public static void main(String args[])
{
• Accessing the private members:- Inner class can access all members of the outer class
Including private members.
-using the object of the outer class ,we can instantiate the inner class as follows:
Outer_Demo outer =new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
Ex:- class Outer
{
private int num=4500; // private variable of the outer class
public class Inner //inner class
{
public int getNum()
{
System.out.println(“This is the getnum method of the inner class”);
return num;
} } }
Public class NestedDemo
{
public static void main(String args[])
{
Outer outer= new Outer(); //instaintiating the outer class
Outer.Inner inner= Outer.new Inner(); // Instaintiating the inner class
System.out.println(“ inner .getNum());
• Method-local Inner class
- In java, we can write a class within a method and this will be a local type . Like local variables, the scope of the inner
class is restricted within the method.
- A method-local inner class can be only within the method where the inner class is defined.
- Ex:- public class OuterClass
{
void outMethod() //instance method of the outer class
{
int num=260;
class InnerClass //method-local inner class
{
public void print()
{
system.out.println(“This is method inner class ” +num);
}
}
InnerClass inner =new InnerClass(); // Accessing the inner class
inner.print();
• Anonymous Inner Class:- An Inner class declared without a class name is known as an
anonymous inner class .
-it is usually declared inside a method or a code block has a curly braces ending with
semicolon and is accessible only at the point where it is defined .
-it does not have a constructor simply because it does not have a name and cannot be
static.
-syntax: AnonymousInner an-inner = new AnonymousInner()
{
public void my_method()
{
…..
}
};
• Static Nested class:- just like static members a static nested class does not have access
to the instance variables and methods of the outer class.
-restriction for static nested class:
i. In java , static class can’t access non-static variables and methods.
ii. It can be accessed by an outer class name.
iii. It can access the static variables and static methods of outer class including private.
• Ex:- public class StaticOuter
{
static class NestedDemo
{
public void myMethod
{
System.out.println(“This is my nested class”);
}
}
public static void main(String args[])
{
StaticOuter.NestedDemo nested= new StaticOuter.NestedDemo();
nested.myMethod();
}
}