SlideShare a Scribd company logo
SHREE SWAMI ATMANAND SARASWATI INSTITUTE
OF TECHNOLOGY
Object Oriented Programming with JAVA(2150704)
PREPARED BY: (Group:2)
Bhumi Aghera(130760107001)
Monika Dudhat(130760107007)
Radhika Talaviya(130760107029)
Rajvi Vaghasiya(130760107031)
Classes, Objects and Method
GUIDED BY:
Prof. Vasundhara Uchhula
Prof. Hardik Nariya
content
• Class
• Object
• Object reference
• Constructor
• Overloading constructor
• Method overloading
• Argument passing and returning object
• Recursion
• New operator
• ‘this’ and ‘static’ keyword
• Finalize() method
• Access control
• Nested and Inner classes
• Anonymous inner class
• Abstract class
Class
• Class is template for an object and object is instance of a class.
• Classes may contain only code or only data, most real-world classes contain both.
• Class is declared by use of the class keyword.
• The data or variables, defined within a class are called instance variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called member of the class.
• In most classes, the instance variables are acted upon and accessed by the methods defined
for that class .
• Thus, it is the method that determine how a class data can be used.
• The general form of a class definition is as follows:
class classname {
type instance-variable1;
type instance-variable2;
type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list){
//body of method
}
}
A simple class example:
class Box
{
double width;
double height;
double depth;
}
• As stated, a class defines a new type of data. In this case, the new data type is called Box. The
important point is that a class declaration only creates a template; it does not create actual
object.
• Thus, the preceding code does not cause any object of type Box to come into existence.
Object
• When we create a class, we are creating a new data type. we can use this type to declare
objects of that type.
• However, obtaining objects of a class is a two-step process.
• First, we must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
• Second, we must acquire an actual, physical copy of the object and assign it to that variable.
We can do this using new operator. The new operator dynamically allocates memory for an
object and returns a reference to it.
• In preceding sample programs, a line similar to the following is used to declare an object type
Box:
Box mybox = new Box();
• This statement combines the two steps. It can be rewritten like this to show each step:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a box object
Object reference
• We can assign value of one object reference variable to another reference variable.
• Reference variable used to store the address of the variables.
• Reference variable will not create distinct copies of objects.
• All reference variables are referring to same object.
• Assigning object reference variables does not allocate memory.
• For example,
Box b1 = new Box();
Box b2 = b1;
• b1 is reference variable which contain the address of actual Box object.
• b2 is another reference variable.
• b2 is initialized with b1 means, b1 and b2 both are referring same object, thus it does not
create duplicate object, nor it allocate extra memory.
Constructors
• Constructor is a special type of method that is used to initialize the object.
• A constructor has same name as the class in which it resides and is syntactically similar to a
method.
• Once defined, the constructor is automatically called immediately after 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
class constructor is the class type itself.
• There are two type of Constructors:
1) Default Constructor
2) Parameterized Constructor
Default Constructor
• A Constructor that have no parameter is known as default Constructor.
• Syntax of default Constructor:
<class_name>(){ }
• For example,
class Box
{ double h,w,d;
Box() // default constructor
{ System.out.println(“constructing Box”);
h=w=d=10;
}
double volume()
{ return w*h*d;
}
}
class Boxdemo
{ public static void main(String args[])
{ Box b = new Box();
System.out.println(“volume is
”+b.volume);
}
}
Output:
constructing Box
volume is 1000.0
Parameterized constructor
• A Constructor that have parameter is known as parameterized Constructor.
• Parameterized Constructor is used to provide different values to the distinct objects of class.
• For example,
class Box
{
double h,w,d;
Box(double height,double width,double depth) // parameterized constructor
{
System.out.println(“constructing Box”);
h = height;
w = width;
d = depth ;
}
Parameterized constructor
double volume() {
return w*h*d;
}
}
class Boxdemo {
public static void main(String args[]) {
Box b = new Box(10,20,15);
System.out.println(“volume is ”+b.volume);
}
}
Output:
constructing Box
volume is 3000.0
Overloading Constructors
• For most real-world classes that you create, overloaded constructors will be the norm, not the
exception.
• The proper overloaded constructor is called based upon the parameters specified when new is
executed.
• Example:
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width=w; height=h; depth=d;
}
Box() {
width=-1; height=-1; depth=-1;
}
Overloading Constructors
Box(double len) {
width=height=depth=len;
}
double volume() {
return width*height*depth;
}
}
public class Overload {
public static void main(String[] args) {
Box mybox1 = new Box(10,20,30);
Box mybox2 = new Box();
Box mybox3 = new Box(5);
double vol;
vol = mybox1.volume();
Overloading Constructors
system.out.println("volume of mybox1 is"+vol);
vol = mybox2.volume();
system.out.println("volume of mybox2 is"+vol);
vol = mybox3.volume();
system.out.println("volume of mybox3 is"+vol);
}
}
Output is:
Volume of mybox1 is 6000.0
Volume of mybox2 is -1.0
Volume of mybox3 is 125.
Method Overloading
• In java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different.
• When this is the case, the method are said to be overloaded, and the process is referred to as
method overloading.
• Method overloading is one of the ways that Java implements polymorphism.
• Overloaded methods must differ in the type and/ or number of their parameters.
• While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
• When Java encounters call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
Example:
class Area
{ int r,b,a;
Method Overloading
void area(int a)
{ return (a*a);
}
void area(int a,int d)
{ return (a*b);
}
void area(int a,int b,int r)
{ return (a*b*r);
}
}
class mainclass
{ public void main(string[] args)
{ area a= new area();
system.out.println(“area of square is: “+a.area(2));
system.out.println(“area of rectangle is: “+a.area(2,3));
Method Overloading
system.out.println(“area of cube is: “+a.area(2,3,5));
}
}
Output:
Area of square is: 4
Area of rectangle is: 6
Area of cube is: 30
• When an overloaded method is called, Java looks for a match between the arguments used to
call the method and the method’s parameters. However, this match need not always be exact.
• In some cases Java’s automatic type conversions can play a role in overload resolution.
Passing an argument
• There are two ways that a computer language can pass an argument to a subroutine. The first
way is 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 you pass a simple 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.
• Example:
// simple types are passed by value.
class test
{ void meth(int i , int j)
{ i * = 2;
j/ =2;
}
}
Passing an argument
class callbyvalue
{
public static void main (string args[ ] )
{
test ob = new test ();
int a = 15, b = 20;
system. out . println("'a and b before call: "' + a + "" "" + b);
ob. meth( a, b);
system.out.printin("a and b after call: " + a + "" "" = b);
}
}
Output:
a and b before call: 15 20
a and b after call: 15 20
Passing an argument
• The second way an argument can be passed is call-by-reference. In this method, a reference to
an argument (not the value of the 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 parameter will affect the argument used to call the subroutine.
• when create a variable of a class type, then required only creating a reference to an object.
• Example:
/ / objects are passed by reference.
class test
{ int a, b;
test (int i, int j)
{ a= i;
b=j;
}
void meth(test o)
Passing an argument
{ o.a * = 2; o.b / = 2;
}
}
Class Callbyref
{ public static void main (string args [ ] )
{ test ob = new test ( 15, 20);
system.out.println ( "ob.a and ob. b before call: "+ ob.a + " " + ob.b) ;
ob.meth (ob);
system.out.println ( " ob.a and ob . b after call: " + ob. a + " " + ob.b ) ;
}
}
Output:
ob. a and ob.b before call: 15 20
ob. a and ob.b after call: 30 10
Returning objects
• A method can return any type of data. Including class types that you create. For example, in
the following program, the incrbyten() method returns an object in which the value of a is ten
greater than it is in the invoking object.
• Example:
class test
{ int a;
test (int i)
{ a = i :
}
test incrbyten ()
{ test temp = new test (a+10);
return temp;
}
}
Returning objects
class retob
{ public static void main (string args []) {
test ob1 = new test(2);
test ob2;
ob2 = ob1 . incrbyten ();
system.out.println("ob1 . a: " + ob1.a) ;
system.out.println("ob2 . a: " + ob2 . a) ;
ob2 = ob2 . incrbyten() ;
system.out.println (""ob2 . a after second increase: ""+ ob2. a ) ;
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
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 numbers between 1 and n.
• Example:
class factorial
{ int fact (int n)
{ int result ;
if(n==1)
{ return 1;
}
result = fact(n-1) * n;
return result;
Recursion
}
}
class recursion
{ public static void main (string args[])
{ factorial f = new factorial ();
system.out.printin("factorial of 3 is " + f.fact(3)) ;
system.out.printin("factorial of 4 is " + f.fact(4));
system.out.printin("factorial of 5 is " + f.fact(5));
}
}
Output:
factorial of 3 is 6
factorial of 4 is 24
factorial of 5 is 120
Recursion
• As each recursive call returns, the old local variables and parameters are removed from the
stack, and execution resumes at the point of the call inside the method.
• Recursion methods could be said to “telescope” out and back.
• Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional functiuon calls.
• Many recursive calls to a method could cause a stack. Because storage for parameters and
local variables is on the stack and each new call creates a new copy of these variables, it is
possible that the stack could be exhausted.
• The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relation.
• For example, the QuickSort sorting algorithms is quite difficult to implement in an iterative
way. Some probles, especially AI-related ones, seem to lend themselves to recursive solution.
New operator
• The new operator dynamically allocates memory for an object during run time. It has
this general form:
class-var = new classname( );
• Here, class-var is a variable of the class type being created. The classname is the name of
the class that is being instantiated. The class name followed by parentheses specifies
the constructor for the class.
• The advantage of this approach is that your program can create as many or as few objects as it
needs during the execution of your program.
• For example: Box b1 = new Box();
Box b2 = b1;
New operator
• b2 is being assigned a reference to a copy of the object referred to by b1. b1 and b2 will both
refer to the same object. The assignment ofb1 to b2 did not allocate any memory or copy any
part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any
changes made to the object through b2 will affect the object to which b1 is referring, since
they are the same object.
• This situation is depicted here:
b1
b2
width
height
depth
Box object
New operator
• Although b1 and b2 both refer to the same object, they are not linked in any other way. For
example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original object.
• When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object, you are only making a copy of the reference.
‘this’ keyword
• this is a reference variable that refers to the current object.
• Usage of java this keyword
i. this keyword can be used to refer current class instance variable.
ii. this() can be used to invoke current class constructor.
iii. this keyword can be used to invoke current class method (implicitly)
iv. this can be passed as an argument in the method call.
v. this can be passed as argument in the constructor call.
vi. this keyword can also be used to return the current class instance.
‘this’ keyword
• this keyword is used from any method or constructor to refer to the current object that calls a
method or invokes constructor .
• Syntax: this.field
‘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 keyword belongs to the class than instance of the class.
• The static can be:
i. Variable (also known as class variable)
ii. Method (also known as class method)
iii. Block
iv. Nested class
Java static method
• If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• static method can access static data member and can change the value of it.
Restrictions for static method
• 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.
Java static variable
• If you declare any variable as static, it is known static variable.
• The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employee, college name of students etc.
• The static variable gets memory only once in class area at the time of class loading.
Java static block
• It used to initialize the static data member.
• It is executed before main method at the time of class loading.
finalize() method
• Sometimes an object will need to perform some action when it is destroyed.
• For example, if an object is holding some non-java resource such as a file handle or window
character font, then you might want to make sure these resources are freed before an object is
destroyed.
• To handle such situations, java provides a mechanism called finalization. By using
finalization, you can define specific actions that will occur when an object is just about to be
reclaimed by the garbage collector.
• To add a finalizer to a class, you simply define the finalize() method. The java run time calls
that method whenever it is about to recycle an object of that class. Inside the finalize() method
you will specify those actions that must be performed before an object is destroyed.
finalize() method
• The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state or indirectly through other referenced objects. Right before an asset is freed,
the java run time calls the finalize() method on the object.
• The finalize() method has this general form:
protected void finalize()
{
// finalization code here
}
• Here, the keyword protected is a specifier that prevents access to finalize() by code defined
outside its class.
Access control
• Through encapsulation, you can control what parts of a program can access the members of a
class. By controlling access, you can prevent misuse.
• For example, allowing access to data only through a well-defined set of methods, you can
prevent the misuse of that data.
• Java’s access specifiers are public, private, and protected. Java also defines a default access
level.
• protected applies only when inheritance is involved.
• When a member of a class is modified by the public specifier, then that member can be
accessed by any other code in your program.
Access control
• When a member of a class is specified as private, then that member can only be accessed by
other members of its class.
• When no access specifier is used, then by default the member of a class is public within its
own package, but cannot be accessed outside of its package.
• An access specifier precedes the rest of a member’s type specification. That is, it must begin a
member’s declaration statement. Here is an example:
public int i;
private double j;
private int myMethod(int a, char b) {//…}
Access control
class Test {
int a;
public int b;
private int c;
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test ();
ob.a = 10;
ob.b = 20;
ob.setc(100);
System.out.println(“a, b, and c:
“ + ob.a + ” “ + ob.b+
“ “+ ob.getc());
}
}
Access control
• Inside the Test class, a uses default access, which for this example is the same as specifying
public. b is explicitly specified as public.
• Member c is given private access. This means that it cannot be accessed by code outside of its
class. So, inside the AccessTest class, c cannot be used directly.
• It must be accessed through its public methods: setc() and getc(). If you were to remove the
comment symbol from the beginning of the following line;
ob.c = 100;
Nested and Inner Classes
• It is possible to define a class within another class; such classes are known as nested classes.
• There are two types of nested classes
1) Static
2) Non-static
• A static nested class is one which has the static modifier applied. Because it is static, it must
access the members of its enclosing class through an object. Because of this, static nested
classes are seldom used.
• An inner class is a non-static nested class. It has access to all of the variables and methods of
its outer class and may refer to them directly as the non-static member of the outer class.
Nested and Inner Classes
Demonstrate an inner class.
Class outer {
int outer_x=100;
void test() {
Inner inner = new Inner();
inner.display();
}
//this is an inner class
class Inner {
void display(){
System.out.print(“display: outer_x = ”+
outer_x );
}
}
}
class InnerClassDemo {
public static voidmain(Stringargs[]) {
Outer outer =new Outer();
outer.test();
}
}
Output:
display: outer_x = 100
Anonymous Inner class
• Inner class without a name is called Anonymous Inner class.
• Anonymous Inner class is a subclass of its original class.
Example:
class Test {
void show() {
System.out.print(“Hello”);
}
}
class AnonDemo {
public static void main(String args[]) {
class AnonDemo {
public static void main(String args[]) {
Test t =new test();
{
void show() {
System.out.print(“Hi,from main”);
}
};
t.show();
}
}
Abstract Class
• Sometimes, we want to define a super class that only declare structure without providing
implementation of every method. It is left to the subclass to fill the details such a superclass is
called abstract class.
• Any class that contains one or more abstract method must be declared abstract.
• There can be no object of abstract class.
• We cannot declare abstract constructor or abstract static method.
• Any subclass of an abstract class must either implement all of the abstract method in the
superclass or be itself declared abstract.
• Syntax for abstract method: abstract type name(parameter-list);
• Syntax for abstract class: abstract classname{
//abstract method or concrete method;
}
Abstract Class
• It must be possible to create a reference to an abstract class so that it can be used to point to a
subclass object.
• Example:
//superclass
abstract class Figure {
double dim1,dim2;
figure(double a, double b) {
dim1=a;
dim2=b;
}
abstract double area(); //abstract method;
}
//subclass
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a,b);
}
double area() {
return dim1*dim2;
}
}
Abstract Class
class maindemo {
public static void main(String args[]) {
Figure f =new Figure(10,10); // illegal
Rectangle r =new Rectangle(9,5);
Figure f; // This is ok, no object is created
f = r;
System.out.println(“Area for rectangle is ”+ f.area() );
}
}
Output:
Area for rectangle is 45
Classes, Objects and Method - Object Oriented Programming with Java

More Related Content

What's hot (20)

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
Abhilash Nair
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
Janki Shah
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
Then Murugeshwari
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
Spotle.ai
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
Somya Bagai
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
Janki Shah
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
Spotle.ai
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
Somya Bagai
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 

Similar to Classes, Objects and Method - Object Oriented Programming with Java (20)

JAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptxJAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
RDeepa9
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
AshokKumar587867
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
JAVA Module 2 ppt on classes and objects and along with examples
JAVA Module 2 ppt on classes and objects and along with examplesJAVA Module 2 ppt on classes and objects and along with examples
JAVA Module 2 ppt on classes and objects and along with examples
Praveen898049
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
Chhom Karath
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
6 Object Oriented Programming
6 Object Oriented Programming6 Object Oriented Programming
6 Object Oriented Programming
Deepak Hagadur Bheemaraju
 
C++ Presen. tation.pptx
C++ Presen.                   tation.pptxC++ Presen.                   tation.pptx
C++ Presen. tation.pptx
mohitsinha7739289047
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
KevinNicolaNatanael
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
JAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptxJAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
RDeepa9
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
JAVA Module 2 ppt on classes and objects and along with examples
JAVA Module 2 ppt on classes and objects and along with examplesJAVA Module 2 ppt on classes and objects and along with examples
JAVA Module 2 ppt on classes and objects and along with examples
Praveen898049
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Ad

More from Radhika Talaviya (16)

General Packet Radio Service(GPRS)
General Packet Radio Service(GPRS)General Packet Radio Service(GPRS)
General Packet Radio Service(GPRS)
Radhika Talaviya
 
The Phases of a Compiler
The Phases of a CompilerThe Phases of a Compiler
The Phases of a Compiler
Radhika Talaviya
 
screen speculo - Miracast android Project
screen speculo - Miracast android Projectscreen speculo - Miracast android Project
screen speculo - Miracast android Project
Radhika Talaviya
 
MICROPROCESSOR AND INTERFACING
MICROPROCESSOR AND INTERFACING MICROPROCESSOR AND INTERFACING
MICROPROCESSOR AND INTERFACING
Radhika Talaviya
 
Assembler - System Programming
Assembler - System ProgrammingAssembler - System Programming
Assembler - System Programming
Radhika Talaviya
 
Cyber Security - Firewall and Packet Filters
Cyber Security - Firewall and Packet Filters Cyber Security - Firewall and Packet Filters
Cyber Security - Firewall and Packet Filters
Radhika Talaviya
 
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Radhika Talaviya
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
Computer Organization
Computer Organization Computer Organization
Computer Organization
Radhika Talaviya
 
Stack
StackStack
Stack
Radhika Talaviya
 
Level, Role, and Skill manager
Level, Role, and Skill  managerLevel, Role, and Skill  manager
Level, Role, and Skill manager
Radhika Talaviya
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
Radhika Talaviya
 
Global environmental essue
Global environmental essueGlobal environmental essue
Global environmental essue
Radhika Talaviya
 
Reflection of girls life
Reflection of girls lifeReflection of girls life
Reflection of girls life
Radhika Talaviya
 
Nanophysics
NanophysicsNanophysics
Nanophysics
Radhika Talaviya
 
I'm ok you're ok
I'm ok you're okI'm ok you're ok
I'm ok you're ok
Radhika Talaviya
 
General Packet Radio Service(GPRS)
General Packet Radio Service(GPRS)General Packet Radio Service(GPRS)
General Packet Radio Service(GPRS)
Radhika Talaviya
 
screen speculo - Miracast android Project
screen speculo - Miracast android Projectscreen speculo - Miracast android Project
screen speculo - Miracast android Project
Radhika Talaviya
 
MICROPROCESSOR AND INTERFACING
MICROPROCESSOR AND INTERFACING MICROPROCESSOR AND INTERFACING
MICROPROCESSOR AND INTERFACING
Radhika Talaviya
 
Assembler - System Programming
Assembler - System ProgrammingAssembler - System Programming
Assembler - System Programming
Radhika Talaviya
 
Cyber Security - Firewall and Packet Filters
Cyber Security - Firewall and Packet Filters Cyber Security - Firewall and Packet Filters
Cyber Security - Firewall and Packet Filters
Radhika Talaviya
 
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Shopping At Mall without standing in Queue for Bill Payment by Scanning Bar c...
Radhika Talaviya
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
Level, Role, and Skill manager
Level, Role, and Skill  managerLevel, Role, and Skill  manager
Level, Role, and Skill manager
Radhika Talaviya
 
Global environmental essue
Global environmental essueGlobal environmental essue
Global environmental essue
Radhika Talaviya
 
Ad

Recently uploaded (20)

FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.
maldonadocesarmanuel
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Transformimet e sinjaleve numerike duke perdorur transformimet
Transformimet  e sinjaleve numerike duke perdorur transformimetTransformimet  e sinjaleve numerike duke perdorur transformimet
Transformimet e sinjaleve numerike duke perdorur transformimet
IndritEnesi1
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.
maldonadocesarmanuel
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Transformimet e sinjaleve numerike duke perdorur transformimet
Transformimet  e sinjaleve numerike duke perdorur transformimetTransformimet  e sinjaleve numerike duke perdorur transformimet
Transformimet e sinjaleve numerike duke perdorur transformimet
IndritEnesi1
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 

Classes, Objects and Method - Object Oriented Programming with Java

  • 1. SHREE SWAMI ATMANAND SARASWATI INSTITUTE OF TECHNOLOGY Object Oriented Programming with JAVA(2150704) PREPARED BY: (Group:2) Bhumi Aghera(130760107001) Monika Dudhat(130760107007) Radhika Talaviya(130760107029) Rajvi Vaghasiya(130760107031) Classes, Objects and Method GUIDED BY: Prof. Vasundhara Uchhula Prof. Hardik Nariya
  • 2. content • Class • Object • Object reference • Constructor • Overloading constructor • Method overloading • Argument passing and returning object • Recursion • New operator • ‘this’ and ‘static’ keyword • Finalize() method • Access control • Nested and Inner classes • Anonymous inner class • Abstract class
  • 3. Class • Class is template for an object and object is instance of a class. • Classes may contain only code or only data, most real-world classes contain both. • Class is declared by use of the class keyword. • The data or variables, defined within a class are called instance variables. • The code is contained within methods. • Collectively, the methods and variables defined within a class are called member of the class. • In most classes, the instance variables are acted upon and accessed by the methods defined for that class . • Thus, it is the method that determine how a class data can be used. • The general form of a class definition is as follows: class classname { type instance-variable1; type instance-variable2; type methodname1(parameter-list) { //body of method } type methodname2(parameter-list){ //body of method } }
  • 4. A simple class example: class Box { double width; double height; double depth; } • As stated, a class defines a new type of data. In this case, the new data type is called Box. The important point is that a class declaration only creates a template; it does not create actual object. • Thus, the preceding code does not cause any object of type Box to come into existence.
  • 5. Object • When we create a class, we are creating a new data type. we can use this type to declare objects of that type. • However, obtaining objects of a class is a two-step process. • First, we must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. • Second, we must acquire an actual, physical copy of the object and assign it to that variable. We can do this using new operator. The new operator dynamically allocates memory for an object and returns a reference to it. • In preceding sample programs, a line similar to the following is used to declare an object type Box: Box mybox = new Box(); • This statement combines the two steps. It can be rewritten like this to show each step: Box mybox; // declare reference to object mybox = new Box(); // allocate a box object
  • 6. Object reference • We can assign value of one object reference variable to another reference variable. • Reference variable used to store the address of the variables. • Reference variable will not create distinct copies of objects. • All reference variables are referring to same object. • Assigning object reference variables does not allocate memory. • For example, Box b1 = new Box(); Box b2 = b1; • b1 is reference variable which contain the address of actual Box object. • b2 is another reference variable. • b2 is initialized with b1 means, b1 and b2 both are referring same object, thus it does not create duplicate object, nor it allocate extra memory.
  • 7. Constructors • Constructor is a special type of method that is used to initialize the object. • A constructor has same name as the class in which it resides and is syntactically similar to a method. • Once defined, the constructor is automatically called immediately after 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 class constructor is the class type itself. • There are two type of Constructors: 1) Default Constructor 2) Parameterized Constructor
  • 8. Default Constructor • A Constructor that have no parameter is known as default Constructor. • Syntax of default Constructor: <class_name>(){ } • For example, class Box { double h,w,d; Box() // default constructor { System.out.println(“constructing Box”); h=w=d=10; } double volume() { return w*h*d; } } class Boxdemo { public static void main(String args[]) { Box b = new Box(); System.out.println(“volume is ”+b.volume); } } Output: constructing Box volume is 1000.0
  • 9. Parameterized constructor • A Constructor that have parameter is known as parameterized Constructor. • Parameterized Constructor is used to provide different values to the distinct objects of class. • For example, class Box { double h,w,d; Box(double height,double width,double depth) // parameterized constructor { System.out.println(“constructing Box”); h = height; w = width; d = depth ; }
  • 10. Parameterized constructor double volume() { return w*h*d; } } class Boxdemo { public static void main(String args[]) { Box b = new Box(10,20,15); System.out.println(“volume is ”+b.volume); } } Output: constructing Box volume is 3000.0
  • 11. Overloading Constructors • For most real-world classes that you create, overloaded constructors will be the norm, not the exception. • The proper overloaded constructor is called based upon the parameters specified when new is executed. • Example: class Box { double width, height, depth; Box(double w, double h, double d) { width=w; height=h; depth=d; } Box() { width=-1; height=-1; depth=-1; }
  • 12. Overloading Constructors Box(double len) { width=height=depth=len; } double volume() { return width*height*depth; } } public class Overload { public static void main(String[] args) { Box mybox1 = new Box(10,20,30); Box mybox2 = new Box(); Box mybox3 = new Box(5); double vol; vol = mybox1.volume();
  • 13. Overloading Constructors system.out.println("volume of mybox1 is"+vol); vol = mybox2.volume(); system.out.println("volume of mybox2 is"+vol); vol = mybox3.volume(); system.out.println("volume of mybox3 is"+vol); } } Output is: Volume of mybox1 is 6000.0 Volume of mybox2 is -1.0 Volume of mybox3 is 125.
  • 14. Method Overloading • In java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. • When this is the case, the method are said to be overloaded, and the process is referred to as method overloading. • Method overloading is one of the ways that Java implements polymorphism. • Overloaded methods must differ in the type and/ or number of their parameters. • While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. • When Java encounters call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. Example: class Area { int r,b,a;
  • 15. Method Overloading void area(int a) { return (a*a); } void area(int a,int d) { return (a*b); } void area(int a,int b,int r) { return (a*b*r); } } class mainclass { public void main(string[] args) { area a= new area(); system.out.println(“area of square is: “+a.area(2)); system.out.println(“area of rectangle is: “+a.area(2,3));
  • 16. Method Overloading system.out.println(“area of cube is: “+a.area(2,3,5)); } } Output: Area of square is: 4 Area of rectangle is: 6 Area of cube is: 30 • When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method’s parameters. However, this match need not always be exact. • In some cases Java’s automatic type conversions can play a role in overload resolution.
  • 17. Passing an argument • There are two ways that a computer language can pass an argument to a subroutine. The first way is 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 you pass a simple 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. • Example: // simple types are passed by value. class test { void meth(int i , int j) { i * = 2; j/ =2; } }
  • 18. Passing an argument class callbyvalue { public static void main (string args[ ] ) { test ob = new test (); int a = 15, b = 20; system. out . println("'a and b before call: "' + a + "" "" + b); ob. meth( a, b); system.out.printin("a and b after call: " + a + "" "" = b); } } Output: a and b before call: 15 20 a and b after call: 15 20
  • 19. Passing an argument • The second way an argument can be passed is call-by-reference. In this method, a reference to an argument (not the value of the 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 parameter will affect the argument used to call the subroutine. • when create a variable of a class type, then required only creating a reference to an object. • Example: / / objects are passed by reference. class test { int a, b; test (int i, int j) { a= i; b=j; } void meth(test o)
  • 20. Passing an argument { o.a * = 2; o.b / = 2; } } Class Callbyref { public static void main (string args [ ] ) { test ob = new test ( 15, 20); system.out.println ( "ob.a and ob. b before call: "+ ob.a + " " + ob.b) ; ob.meth (ob); system.out.println ( " ob.a and ob . b after call: " + ob. a + " " + ob.b ) ; } } Output: ob. a and ob.b before call: 15 20 ob. a and ob.b after call: 30 10
  • 21. Returning objects • A method can return any type of data. Including class types that you create. For example, in the following program, the incrbyten() method returns an object in which the value of a is ten greater than it is in the invoking object. • Example: class test { int a; test (int i) { a = i : } test incrbyten () { test temp = new test (a+10); return temp; } }
  • 22. Returning objects class retob { public static void main (string args []) { test ob1 = new test(2); test ob2; ob2 = ob1 . incrbyten (); system.out.println("ob1 . a: " + ob1.a) ; system.out.println("ob2 . a: " + ob2 . a) ; ob2 = ob2 . incrbyten() ; system.out.println (""ob2 . a after second increase: ""+ ob2. a ) ; } } Output: ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
  • 23. 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 numbers between 1 and n. • Example: class factorial { int fact (int n) { int result ; if(n==1) { return 1; } result = fact(n-1) * n; return result;
  • 24. Recursion } } class recursion { public static void main (string args[]) { factorial f = new factorial (); system.out.printin("factorial of 3 is " + f.fact(3)) ; system.out.printin("factorial of 4 is " + f.fact(4)); system.out.printin("factorial of 5 is " + f.fact(5)); } } Output: factorial of 3 is 6 factorial of 4 is 24 factorial of 5 is 120
  • 25. Recursion • As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method. • Recursion methods could be said to “telescope” out and back. • Recursive versions of many routines may execute a bit more slowly than the iterative equivalent because of the added overhead of the additional functiuon calls. • Many recursive calls to a method could cause a stack. Because storage for parameters and local variables is on the stack and each new call creates a new copy of these variables, it is possible that the stack could be exhausted. • The main advantage to recursive methods is that they can be used to create clearer and simpler versions of several algorithms than can their iterative relation. • For example, the QuickSort sorting algorithms is quite difficult to implement in an iterative way. Some probles, especially AI-related ones, seem to lend themselves to recursive solution.
  • 26. New operator • The new operator dynamically allocates memory for an object during run time. It has this general form: class-var = new classname( ); • Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. • The advantage of this approach is that your program can create as many or as few objects as it needs during the execution of your program. • For example: Box b1 = new Box(); Box b2 = b1;
  • 27. New operator • b2 is being assigned a reference to a copy of the object referred to by b1. b1 and b2 will both refer to the same object. The assignment ofb1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. • This situation is depicted here: b1 b2 width height depth Box object
  • 28. New operator • Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2. For example: b1 = null; • Here, b1 has been set to null, but b2 still points to the original object. • When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.
  • 29. ‘this’ keyword • this is a reference variable that refers to the current object. • Usage of java this keyword i. this keyword can be used to refer current class instance variable. ii. this() can be used to invoke current class constructor. iii. this keyword can be used to invoke current class method (implicitly) iv. this can be passed as an argument in the method call. v. this can be passed as argument in the constructor call. vi. this keyword can also be used to return the current class instance.
  • 30. ‘this’ keyword • this keyword is used from any method or constructor to refer to the current object that calls a method or invokes constructor . • Syntax: this.field
  • 31. ‘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 keyword belongs to the class than instance of the class. • The static can be: i. Variable (also known as class variable) ii. Method (also known as class method) iii. Block iv. Nested class
  • 32. Java static method • If you apply static keyword with any method, it is known as static method. • A static method belongs to the class rather than object of a class. • A static method can be invoked without the need for creating an instance of a class. • static method can access static data member and can change the value of it. Restrictions for static method • 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.
  • 33. Java static variable • If you declare any variable as static, it is known static variable. • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employee, college name of students etc. • The static variable gets memory only once in class area at the time of class loading. Java static block • It used to initialize the static data member. • It is executed before main method at the time of class loading.
  • 34. finalize() method • Sometimes an object will need to perform some action when it is destroyed. • For example, if an object is holding some non-java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. • To handle such situations, java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. • To add a finalizer to a class, you simply define the finalize() method. The java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize() method you will specify those actions that must be performed before an object is destroyed.
  • 35. finalize() method • The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the java run time calls the finalize() method on the object. • The finalize() method has this general form: protected void finalize() { // finalization code here } • Here, the keyword protected is a specifier that prevents access to finalize() by code defined outside its class.
  • 36. Access control • Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. • For example, allowing access to data only through a well-defined set of methods, you can prevent the misuse of that data. • Java’s access specifiers are public, private, and protected. Java also defines a default access level. • protected applies only when inheritance is involved. • When a member of a class is modified by the public specifier, then that member can be accessed by any other code in your program.
  • 37. Access control • When a member of a class is specified as private, then that member can only be accessed by other members of its class. • When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. • An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s declaration statement. Here is an example: public int i; private double j; private int myMethod(int a, char b) {//…}
  • 38. Access control class Test { int a; public int b; private int c; void setc(int i) { c = i; } int getc() { return c; } } class AccessTest { public static void main(String args[]) { Test ob = new Test (); ob.a = 10; ob.b = 20; ob.setc(100); System.out.println(“a, b, and c: “ + ob.a + ” “ + ob.b+ “ “+ ob.getc()); } }
  • 39. Access control • Inside the Test class, a uses default access, which for this example is the same as specifying public. b is explicitly specified as public. • Member c is given private access. This means that it cannot be accessed by code outside of its class. So, inside the AccessTest class, c cannot be used directly. • It must be accessed through its public methods: setc() and getc(). If you were to remove the comment symbol from the beginning of the following line; ob.c = 100;
  • 40. Nested and Inner Classes • It is possible to define a class within another class; such classes are known as nested classes. • There are two types of nested classes 1) Static 2) Non-static • A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. Because of this, static nested classes are seldom used. • An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly as the non-static member of the outer class.
  • 41. Nested and Inner Classes Demonstrate an inner class. Class outer { int outer_x=100; void test() { Inner inner = new Inner(); inner.display(); } //this is an inner class class Inner { void display(){ System.out.print(“display: outer_x = ”+ outer_x ); } } } class InnerClassDemo { public static voidmain(Stringargs[]) { Outer outer =new Outer(); outer.test(); } } Output: display: outer_x = 100
  • 42. Anonymous Inner class • Inner class without a name is called Anonymous Inner class. • Anonymous Inner class is a subclass of its original class. Example: class Test { void show() { System.out.print(“Hello”); } } class AnonDemo { public static void main(String args[]) { class AnonDemo { public static void main(String args[]) { Test t =new test(); { void show() { System.out.print(“Hi,from main”); } }; t.show(); } }
  • 43. Abstract Class • Sometimes, we want to define a super class that only declare structure without providing implementation of every method. It is left to the subclass to fill the details such a superclass is called abstract class. • Any class that contains one or more abstract method must be declared abstract. • There can be no object of abstract class. • We cannot declare abstract constructor or abstract static method. • Any subclass of an abstract class must either implement all of the abstract method in the superclass or be itself declared abstract. • Syntax for abstract method: abstract type name(parameter-list); • Syntax for abstract class: abstract classname{ //abstract method or concrete method; }
  • 44. Abstract Class • It must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. • Example: //superclass abstract class Figure { double dim1,dim2; figure(double a, double b) { dim1=a; dim2=b; } abstract double area(); //abstract method; } //subclass class Rectangle extends Figure { Rectangle(double a, double b) { super(a,b); } double area() { return dim1*dim2; } }
  • 45. Abstract Class class maindemo { public static void main(String args[]) { Figure f =new Figure(10,10); // illegal Rectangle r =new Rectangle(9,5); Figure f; // This is ok, no object is created f = r; System.out.println(“Area for rectangle is ”+ f.area() ); } } Output: Area for rectangle is 45