You are on page 1of 28

Classes, 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.

Class in Java: Class is also called as blueprint of object.


A class defines new data type .It represents the set of properties or methods that are
common to all objects of one type.
-Properties are represented by variables and actions are represented by methods.
-class consists of variables and methods.
Class declaration :
1.Modifier: a class can be public or default.
2.Class keyword: class keyword is used to create a class.
3.Class name: the name should begin with an capitalized letter.
4.Superclass: the name of the parent , if any preceded by the keyword extended .
5.Interfaces: A common separated list of interfaces implemented by the class if any
preceded by the keyword implements.
6.Body: the class body surrounded by braces { }.

-Syntax: class classname


{
field declaration;
method declaration;
}
Ex: class Students
{
int rollno; //fields
String sname; //fields
int age; //fields
void get_info( int r, String s , int a) //method1
{
rollno=r;
sname=s;
age=a;
}
void print_info() //method2
{
System.out.println(“Student roll no. : ” +rollno);
System.out.println(“Student name : ” +sname);
System.out.println(“Student age : ” +age);
}
}
• Object in java: An object in java created from a class, can be physical or logical.
-physical objects can be cell _phone, car, person
-logical objects can be bank_account.

Syntax: ClassName variable_name = new ClassName/constructor();


Ex: Student stud=new Student();
Here stud is an object of that represent the class Student during runtime.
new keyword creates an actual physical copy of the object and assigns it to the stud
variable.
• Object Reference: An object reference is information on how to find a particular object.
-This object is a chunk of main memory.
-A reference to the object is a way to get to that chunk of variable.
-Objects are created while a program is running .Each object has a unique object reference,
which is used to find it .
-When an object reference is assigned to a variable ,then that variable says how to find that
object.
Ex: 1)String str1= new String(“Java”);
String str2= new String(“java”);
//then
Str1== str2; //is false
Str1.equals(str2); //is true
2)String str1= new String(“java”);
String str2=str1;
Str1==Str2 //is true
Str1.equals(str2) //is true
• Accessing Class Members: The values can be assigned to the variables in different
ways.
- We cannot access the methods outside of the directly .
- It is possible to access the variables and methods by using the concerned object and
dot(.) operator.
- Syntax: Object_name.variable_name=value; //variable
Object_name.method_name(parameter-list); //method
Constructor: Constructor overloading
Sometimes we need to initialize the data members in the class . For this reason ,constructor have been defined in
the class.
-A constructor are special member functions which are invoked or called when the object is instantiated .
-At the time of calling constructor , memory for the object is allocated in the memory.
-Every time an object is created using the new keyword , at least one constructor is called.
-It calls a default constructor by default. Constructor are similar in syntax to methods , but without any return
type and have the same name as that of the class.
Ex: public MyClass
{
MyClass()
{
}
}
• points to remember while defining constructor: Constructor have the same name as that of class.
-Constructor are similar to methods in syntax , but constructor do not have a return type ,should not specify
void.
- Constructor can also be overload just like methods.
- Constructor can be invoked only during object creation or from other construction using this keyword.
• There are two types of constructor in Java:
1.Default constructor.
2.Parameterized Constructor.
1.Default constructor: A constructor is called “Default Constructor” when it doesn’t have any parameter .
The default constructor is used to provide the default values to the object like 0 or null.
-Every class is having constructor by default ,if we don’t create a class constructor ,java creates it implicitly in
the class.
Ex: class MyClass
{
MyClass()
{
System.out.println(“This is default constructor”); //default constructor
}
public static void main(String args[])
{
MyClass obj= new MyClass(); //default constructor called
}
}
2) Parameterised Construction: A constructor which has a specify number of parameters is
called a parameterized constructor .We can have any number of parameterized
constructor in our class.
- Method: Method Overloading , Recursion ,Passing and Returning Object from Method
Method: A method is a collection of statements that perform some specific task and
returns the result to the caller.
-Polymorphism in Java: Polymorphism in Java is a concept by which we can perform a
single action in different ways. Polymorphism is derived from 2 Greek words: Poly and
morphs.
-The word “poly” means many and “morphs” means forms. So polymorphism means many
forms.
-There are two types of polymorphism in java: Compile-time polymorphism and runtime
polymorphism .
-We can perform polymorphism in java by method overloading and method overriding.
1] Compile Time Polymorphism (Method Overloading):-Polymorphism that is resolved
during compiler time is known as static polymorphism.
-Method overloading is an example of Compile time Polymorphism.
• Method Overloading: In Java ,it is possible to create methods with the same name and different
parameters with different definitions. This is called as method overloading .
-Method overloading is a concept of java in which we can create multiple methods of the same name in
the same class, and all methods work in different ways.
- Method Overloading is one of the ways through which java supports polymorphism .
- There are two ways to overload the method in java:
i)By changing the number of arguments
ii) By changing the data type.
-Program Shape.java

• 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();
}
}

You might also like