Classes, Objects and Methods
OBJECT ORIENTED PROGRAMMING USING JAVA
LECTURER: Dr. KRUNAL PATEL
MBIT ENGGINEERING COLLEGE
NEW VALLABH VIDYANAGAR
OOPS
(Object Oriented Programming System)
• Object means a real word entity such as pen, chair, table etc.
• Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
• It simplifies the software development and maintenance by providing some
concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
OOPS
(Object Oriented Programming System)
Object
• Any entity that has state and behaviour is known as an object.
• For example: chair, pen, table, keyboard, bike etc.
Class
• Collection of objects is called class. It is a logical entity.
Inheritance
• When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
OOPS
(Object Oriented Programming System)
Polymorphism
• When one task is performed by different ways i.e. known as polymorphism.
• For example: to convenes the customer differently, to draw something e.g. shape or rectangle
etc.
• In java, we use method overloading and method overriding to achieve polymorphism.
• Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
• Hiding internal details and showing functionality is known as abstraction.
• For example: phone call, we don't know the internal processing.
• In java, we use abstract class and interface to achieve abstraction.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
OOPs (Object Oriented Programming System)
Encapsulation
• Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
• For example: capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Introduction
• What is class?
Class is a collection of data members and member functions.
• Now what are data members?
Data members are nothing but simply variables that we declare inside
the class so it called data member of that particular class
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Introduction
• Now what are member functions?
• Member functions are the function or you can say methods which we declare
inside the class so it called member function of that particular class.
• The most important thing to understand about a class is that it defines a new
data type.
• Once defined, this new type can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance of a class.
• Because an object is an instance of a class, you will often see the two words
object and instance used interchangeably
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax of Class
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax of Class
• When you define a class, you declare its exact form and nature.
• You do this by specifying the data that it contains and the code that operates on
that data.
• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• NOTE : C++ programmers will notice that the class declaration and the
implementation of the methods are stored in the same place and not defined
separately.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax of Class
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax
• accessing data member of the class:
objectname.datamembername;
• accessing methods of the class:
objectname.methodname();
So for accessing data of the class:
we have to use (.) dot operator.
NOTE: we can use or access data of any particular class without using (.) dot
operator from inside that particular class only.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax of object
//declaration of object
classname objectname;.
//allocate memory to object (define object).
objectname = new classname();
or we can directly define object like this
classname objectname = new classname();
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Introduction To Method
• As we all know that, classes usually consist of two things instance variables
and methods.
• Here we are going to explain some fundamentals about methods.
• So we can begin to add methods to our classes.
• Methods are defined as follows
§ Return type
§ Name of the method
§ A list of parameters
§ Body of the method.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax
return type method name (list of parameters)
{
Body of the method
}
• return type specifies the type of data returned by the method. This
can be any valid data type including class types that you create.
• If the method does not return a value, its return type must be void,
Means you can say that void means no return.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax
• Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
return value;
• Here, value is the value returned.
• The method name is any legal identifier.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax
• The list of parameter is a sequence of type and identifier pairs
separated by commas.
• Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.
• If the method has no parameters, then the parameter list will be
empty.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Syntax
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors
• The Constructor is named exactly the same as the class.
• The Constructor is called when the new keyword is used.
• The Constructor cannot have any return type —not even void
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors
• The Constructor instantiates the object.
• It initializes instance variables to acceptable values.
• The “default” Constructor accepts no arguments.
• The Constructor method is usually overloaded
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Difference between constructor and method in
java
Java Constructor Java Method
ü Constructor is used to initialize the state ü Method is used to expose behaviour of
of an object. an object.
ü Constructor must not have return type. ü Method must have return type.
ü Constructor is invoked implicitly. ü Method is invoked explicitly.
ü The java compiler provides a default ü Method is not provided by compiler in
constructor if you don't have any any case.
constructor.
ü Constructor name must be same as the ü Method name may or may not be same
class name. as class name.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Varieties of Methods: Constructors
• The overloaded Constructor usually takes arguments.
• That allows the class to be instantiated in a variety of ways.
• If the designer neglects to include a constructor, then the compiler
creates a default constructor that takes no arguments.
• A default constructor will call the Constructor for the class this one
extends.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Varieties of Methods: Constructors
public Time2()
{
setTime( 0, 0, 0 );
}
• This is the first Constructor.
• Notice that it takes no arguments, but it still sets the instance
variables for hour, minute and second to consistent initial values of
zero.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Varieties of Methods: Constructors
public Time2()
{
setTime( 0, 0, 0 );
}
public Time2( int h, int m, int s )
{
setTime( h, m, s );
}
• These are the first two Constructors.
• The second Constructor takes arguments.
• It still calls the setTime() method so it can validate the data.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors overloading
• Constructors Along with method overloading, we can also overload
constructors.
• Constructors having the same name with different parameter list is
called constructor overloading
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors overloading
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors overloading
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors overloading
• Above program is quite complicated here I am giving you perfect flow of
program.
• First of all note one thing that new ClassName() this is a short syntax of
creating object of any class.
• And we all know that when we create object the constructor of that class
will be called automatically.
• So in our program first of all due to syntax Circlec1 = new Circle(); non
parameterize constructor will be called for object c1 so we get output like
Centre at 5 and 5 Radius = 3 in c1.display().
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Constructors overloading
• Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3 arguments
will be called for object c2 so we get output like Centre at 10 and 20 Radius = 5 in
c2.display().
• Now when we define object c3 our syntax is like Circle c3 = new Circle(new
Point(15,25),10); so first of all it will create object for Point class so constructor of point
class will be called and it will set parameter x and y.
• Then constructor of circle class which has Point class object as an argument along with
one int argument will be called and set all parameter as per program and we get output
like Centre at 15 and 25 Radius = 10 in c3.display().
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Method Overloading
• A class can contain any number of methods. Methods can be with
parameter and without parameter.
• The parameter in a method are called type signature.
• It is possible in java to define two or more methods within the same class
that share the same name, but with different parameter declarations (type
signatures).
• When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Method Overloading
• Overloading methods demonstrate the concept of polymorphism.
• When an overloaded method is invoked, java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to call.
• Thus, overloaded methods must differ in the type and/or number of
their parameters.
• Overloaded methods may have different return types
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Method Overloading
• When java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the
arguments used in the call.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Method Overloading
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Method Overloading
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
More About Method
1. Passing Objects as a Parameter to Method.
2. Method overloading with object as a parameter.
3. Return an Object
• We have seen that methods can take parameters as input and process
them.
• It is also common to pass objects as a parameter to methods.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
1. Passing Objects as a Parameter to Method.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
2. Method overloading with object as a parameter.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
2. Method overloading with object as a parameter.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
3. Return an Object
• A method can return any type of data, including class type (object)
that you create.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
3. Return an Object
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
3. Return an Object
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
3. Return an Object
• RetObj multiply(RetObj p1, RetObj p2) this is the syntax in our
program which has return type object.
• obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method
multiply and return object, it will store in obj3.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Value
Now we all know that how to define and call the methods.
• There are two types of calling method and those are
1. call by value
2. call by reference
• Here we illustrate call by value and in next topic we will look at call by reference.
• In call by value when we call any method we pass value as method parameter so
changing in local variables of the method doesn‘t affect the original variables of
class.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Value
• This method copies the value of an argument into the formal
parameter of the subroutine.
• Therefore, changes made to the parameter of the subroutine have no
effect on the argument.
• In java, when we pass a primitive type to a method, it is passed by
value.
• Thus, what occurs to the parameter that receives the argument has
no effect outside the method.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Value
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Value
• You can see that after calling method we change value of a and b but
it will not affect the original value of class` members because of call
by value.
• We pass value v.a and v.b as parameter and it will change local
method`s a and b variables.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Reference
• Here we pass reference as parameter in function calling.
• We all know that reference means object so we pass object as parameter.
• A reference to an argument (not value of argument) is passed to the
parameter.
• Inside the subroutine, this reference is used to access the actual argument
specified in the call.
• This means that changes made to the parameters will affect the argument
used to call the subroutine
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Reference
• When we pass an object to a method, the situation changes, because objects are
passed by call-by-reference.
• When we create a variable of a class type, we are only creating a reference to an
object. Thus, When you pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the argument.
• This effectively means that objects are passed to method do affect the object
used as an argument.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Reference
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Call By Reference
• You can see that after calling method value of original a and b is
changed because of call by reference.
• Here we pass "r" reference (Object) as parameter in method calling.
So changes inside method will affect original variable of class
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Recursion
• Recursion is the process of defining something in terms of itself.
• When function call it self is called recursion.
• A method that calls itself is said to be recursive.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Recursion
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Recursion
• Here the method fact is recursive because it calls itself.
• The whole process something like this
• result = fact(7-1) * 7 and so on until it returns 1.
• So one thing is sure that we have to take care that in every recursive
process there must be a terminate condition to come out from recursion.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
This Keyword
• There can be a lot of usage of java this keyword.
• In java, this is a reference variable that refers to the current object.
• we are using this keyword to distinguish between local variable and instance
variable.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Static Keyword
• The static keyword in java is used for memory management mainly.
• We can apply java static keyword with variables, methods, blocks and nested
class.
• The static can be:
• variable (also known as class variable)
• method (also known as class method)
• Block
• nested classes
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Restrictions for static method
• There are two main restrictions for the static method. They are:
• The static method can not use non static data member or call non-static method directly.
• this and super cannot be used in static context.
Example:
class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Java static block
• Is used to initialize the static data member.
• It is executed before main method at the time of class loading.
class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Final Keyword In Java
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many context.
Final can be:
• Variable : final int a;
• Method : final void run()
• Class : final class Hello{}
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Final Keyword In Java
• Stop Value change
• Stop Method Overriding
• Stop Inheritance
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Impact on Access Modifiers
• The familiar private access modifier lets us shield our instance
variables from the outside world.
• Relying on Access Modifiers, you can shield both your class’s private
instance variables and its private methods
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Impact on Access Modifiers
• Java lets review the four different levels of access:
private,
protected,
public
and the default if you don’t specify package.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
• Therefore, the important point
Subclasses can reach protected-access variables, but can’t reach
package-access variables…
unless the Subclasses happen to be saved in the same package
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Access Modifiers
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
private
Impact on Access Modifiers: private
• When my class inherits from a Superclass, I cannot access the
Superclass’s private data variables. Private data is Secret!
• In other words, the Subclass cannot automatically reach the private
data variables of the Superclass.
• A private data variable is accessible only to the class in which it is
defined
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
private
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
private
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Package
Varieties of Access Modifiers: package
• If you do not specify the access for either a method or an
encapsulated data variable, then it is given the default access:
package
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Package
Varieties of Access Modifiers: package
• This access allows other classes in the same package as your class to
access its data variables as if they were their own.
package
• This level of access assumes that classes in the same package as your
class are friends who won’t harm your class’ data
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Package
• Notice that no access modifier is declared.
• So, iamprivate and method private Method both default to package
access.
• All classes declared in the package Greek, along with class Delta, have
access to iamprivate and private Method
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Package
• So, when you don’t include any access modifier, you are in fact giving
your variable package access.
int x; // package access instance variable
• Notice, it’s declared neither public nor private
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Protected
• protected allows the class itself, Subclasses and all classes in the same
package to access the members.
• Generally speaking, protected offers greater access than package
access.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Protected
• Use the protected access level when it’s appropriate for a class’s
Subclasses to have access to the member, but not for unrelated
classes to have access.
• protected members are like family secrets— you don’t mind if
someone in the family knows— but you don’t want outsiders to know
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Protected
• A Superclass’s protected data variables may be accessed only by:
—methods of the Superclass
—methods of the Subclass
—methods of other classes in the same package.
Or we can summarize:
protected members have package access.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Finalize() Method : Garbage Collection
• In Java destruction of object from memory is done automatically by
the JVM.
• When there is no reference to an object, then that object is assumed
to be no longer needed and the memory occupied by the object are
released.
• This technique is called Garbage Collection.
• This is accomplished by the JVM.
• Unlike C++ there is no explicit need to destroy object.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Finalize() Method : Garbage Collection
• Advantages of Garbage Collection
• Programmer doesn't need to worry about dereferencing an object.
• It is done automatically by JVM.
• Increases memory efficiency and decreases the chances for memory leak.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Finalize() Method : Garbage Collection
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 clean-up utility.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Finalize() Method : Garbage Collection
Signature of finalize() method
protected void finalize()
{
//finalize-code
}
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested/inner Classes
• It is possible to define a class within another class; such classes are
known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing
class.
• That means, if class B is defined within class A, then B is known to A,
but not outside A.
• Without existing one type of object there is no chance of existing
other type of object then go for inner classes or nested classes
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
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.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested/inner Classes
• There are two types of nested classes:
1. Static
2. Non – Static
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested/inner Classes
• Static nested class :- A static nested class is one which has the static
modifier.
• Because it is static it cannot refer to non-static members of its
enclosing class directly.
• Because of this restriction static nested class is seldom used.
• It can be accessed by outer class name.
• It can access static data members of outer class including private.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
• Non – Static nested class :- Non – Static nested class is known as
inner class.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
• Non – Static nested class :- Non – Static nested class is known as
inner class.
• It has access to all of its variables and methods of its outer class and
can refer to them directly.
• An inner class is fully within the scope of its enclosing class
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
Anonymous inner class
• A class that have no name is known as anonymous inner class in java.
• It should be used if you have to override method of class or interface.
• They enable you to declare and instantiate a class at the same time.
Java Anonymous inner class can be created by two ways:
• Class (may be abstract or concrete).
• Interface
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
• Internal working of given code
Person p=new Person()
{
void eat()
{
System.out.println("nice fruits");
}
};
• A class is created but its name is decided by the compiler which extends the
Person class and provides the implementation of the eat() method.
• An object of Anonymous class is created that is referred by p reference variable of
Person type.
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Nested Classes
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Let us see one more example but here the
program will not compile
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Let us see one more example but here the
program will not compile
• Here, y is declared as an instance variable of Inner.
• Thus it is not known outside Of that class and it cannot be used by
showy( ).
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Command Line Argument
• Sometimes you will want to pass information into a program when you run
it. This is accomplished by passing command-line arguments to main( ).
• A command-line argument is the information that directly follows the
program’s name on the command line when it is executed.
• To access the command-line arguments inside a Java program is quite
easy—they are stored as strings in the String array passed to main( ).
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Command Line Argument
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT
Command Line Argument
Dr. KRUNAL N. PATEL (IT DEPARTMENT), MBIT