Chapter 6



Classes And Method



                 http://www.java2all.com
Method Overloading



                 http://www.java2all.com
•     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.
                                           http://www.java2all.com
•       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.
                                            http://www.java2all.com
•      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.




                                            http://www.java2all.com
public class MethodOver
{
       int n1;
       int n2;
       MethodOver()
       {
            n1 = 10;
            n2 = 20;
       }
       void square()
       {
            System.out.println("The Square is " + n1 * n2);
       }
       void square(int p1)
       {
            n1 = p1;
            System.out.println("The Square is " + n1 * n2);
       }
       void square(int p1, int p2)
       {
            n1 = p1;
            n2 = p2;
            System.out.println("The Square is " + n1 * n2);
       }
       public static void main(String args[])
       {
            MethodOver obj1 = new MethodOver();
            obj1.square(); //call non parameterise method
            obj1.square(4); //call method which has 1 argument
            obj1.square(7,8); //call method which has 2 argument
       }
                                                                   http://www.java2all.com
public class MethodOver
{
       int n1;
       int n2;
       MethodOver()
       {
            n1 = 10;
            n2 = 20;
       }
       void square()
       {
            System.out.println("The Square is " + n1 * n2);
       }
           Output :
       void square(int p1)
       {
            n1 = p1;
            System.out.println("The Square is " + n1 * n2);
       }   The Square is 200
       void square(int p1, int p2)
       {   The Square is 80
            n1 = p1;
           The Square is 56
            n2 = p2;
            System.out.println("The Square is " + n1 * n2);
       }   You can see that here we have 3 square
       public static void main(String args[])
       {   methods with different argument.
            MethodOver obj1 = new MethodOver();
           Its called method overloading.
            obj1.square(); //call non parameterise method
            obj1.square(4); //call method which has 1 argument
            obj1.square(7,8); //call method which has 2 argument
       }
                                                                   http://www.java2all.com
Constructors overloading




                      http://www.java2all.com
Constructors

      Along with method overloading, we can
also overload constructors.

      Constructors having the same name with
different parameter list is called constructor
overloading.




                                            http://www.java2all.com
class Point
{
     int x;
     int y;
     Point(int a, int b)
     {
          x = a;
          y = b;
     }

}
class Circle
{
     int originX;
     int originY;
     int radius;

     //Default Constructor

     Circle()
     {
         originX = 5;
         originY = 5;
         radius = 3;

     }
// Constructor initializing the coordinates of origin and the radius.
                                                                        http://www.java2all.com
Circle(int x1, int y1, int r)
    {
         originX = x1;
         originY = y1;
         radius = r;
    }
    Circle(Point p, int r)
    {
         originX = p.x;
         originY = p.y;
         radius = r;
    }
     void display()
    {
         System.out.println("--Center at " + originX + " and " + originY);
         System.out.println("Radius = " + radius);
    }
    public static void main(String args[])
    {

          Circle c1 = new Circle();
          Circle c2 = new Circle(10,20,5);
          Circle c3 = new Circle(new Point(15,25),10);
          c1.display();
          c2.display();
          c3.display();
    }
}                                                                            http://www.java2all.com
Circle(int x1, int y1, int r)
    {
         originX = x1;
         originY = y1;
         radius = r;
    }
    Circle(Point p, int r)
    {
         originX = p.x;
         originY = p.y;
         radius = r;
    }
     void display()
    {                   Output :
                        --Center at 5 and 5
         System.out.println("--Center at " + originX + " and " + originY);
         System.out.println("Radius = " + radius);
    }                   Radius = 3
    public static void main(String args[])
    {                   --Center at 10 and 20
          Circle c1 = new Circle(); = 5
                        Radius
                        --Center at 15 and 25
          Circle c2 = new Circle(10,20,5);
          Circle c3 = new Circle(new Point(15,25),10);
          c1.display(); Radius = 10
          c2.display();
          c3.display();
    }
}                                                                            http://www.java2all.com
Above program is quite complicated here i am
giving you perfect flow of program.

      First of all note one thing that
newClassName() 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 Circle
c1 = new Circle(); non parameterize constructor will be
called for object c1 so we get output like Center at 5 and
5 Radius = 3 in c1.display().

                                                    http://www.java2all.com
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 Center 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 Center at 15 and 25 Radius = 10 in
c3.display().
                                                      http://www.java2all.com
More About Method



                http://www.java2all.com
1. Passing Objects as a Parameter to Method.


      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.




                                           http://www.java2all.com
class PassObj
{
     int n1;
     int n2;
      PassObj() // constructor
     {
          n1 = 0;
          n2 = 0;
     }
     PassObj(int p1, int p2)                                 Output :
     {
          n1 = p1;
          n2 = p2;                                           Multiplication is
     }
     void multiply(PassObj p1)                               30
     {
          int temp;
          temp = p1.n1 * p1.n2;
          System.out.println("Multiplication is " + temp);
     }
     public static void main(String args[])
     {
          PassObj obj1 = new PassObj(5,6);
          PassObj obj2 = new PassObj();
          obj2.multiply(obj1);
     }
}
                                                                        http://www.java2all.com
2. Method overloading with object as a parameter
 class MetObjOv
 {
      int n1;
      int n2;

     // constructor
     MetObjOv()
     {
          n1 = 0;
          n2 = 0;
     }
     MetObjOv(int x, int y)
     {
          n1 = x;
          n2 = y;
     }
     void multiply(MetObjOv p1)
     {
          n1 = p1.n1;
          n2 = p1.n2;
          System.out.println("There is nothing to multiply ");
          System.out.println("n1 = "+n1+"tn2 = " +n2);
     }


                                                                 http://www.java2all.com
void multiply(MetObjOv p1, MetObjOv p2)
    {
         n1 = p1.n1 * p2.n1;
         n2 = p1.n2 * p2.n2;

         System.out.println("Multiplication of two objects ");
         System.out.println("n1 = " + n1 + "tn2 = " + n2 );
    }

    public static void main(String args[])
    {
         MetObjOv obj1 = new MetObjOv(5,6);
         MetObjOv obj2 = new MetObjOv(6,5);
         MetObjOv obj3 = new MetObjOv();
         obj3.multiply(obj1);
         obj3.multiply(obj1, obj2);
    }
}       Output :
        There is nothing to multiply
        n1 = 5 n2 = 6
        Multiplication of two objects
        n1 = 30 n2 = 30
                                                                 http://www.java2all.com
3. Return an Object.



  A method can return any type of
  data, including class type (object)
           that you create.




                                 http://www.java2all.com
class RetObj
{
     int n1;
     int n2;

    // constructor
    RetObj()
    {
         n1 = 0;
         n2 = 0;
    }
    RetObj(int x, int y)
    {
         n1 = x;
         n2 = y;
    }
    RetObj multiply(RetObj p1, RetObj p2)
    {
         n1 = p1.n1 * p2.n1;
         n2 = p1.n2 * p2.n2;
         return (this);
    }

    void display()
    {
         System.out.println("An Example of returning an Object ");
         System.out.println("n1 = "+n1+"tn2 = " +n2);
    }                                                                http://www.java2all.com
public static void main(String args[])
    {
        RetObj obj1 = new RetObj(5,6);
        RetObj obj2 = new RetObj(6,5);
        RetObj obj3 = new RetObj();
        obj3 = obj3.multiply(obj1, obj2);
        obj3.display();
    }
}
      Output :
      An Example of returning an
      Object
      n1 = 30 n2 = 30

       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.
                                                                    http://www.java2all.com
Call By Value



            http://www.java2all.com
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.                  http://www.java2all.com
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.

                                            http://www.java2all.com
public class CallBy_Value
{
   public static void main(String[] args)
   {
     Value v = new Value(10,20);
     System.out.println("a and b before call............");
     System.out.println("a = "+v.a);
     System.out.println("b = "+v.b);
     v.call(v.a,v.b);      // CALL BY VALUE
     System.out.println("a and b after call............");
     System.out.println("a = "+v.a);
     System.out.println("b = "+v.b);
   }
}
class Value                  Output :
{
   int a,b;
   Value(int i,int j)        a and b before call............
   {
     a=i;                    a = 10
     b = j;
   }                         b = 20
   void call(int a, int b)
   {
                             a and b after call............
     a = a * 2;              a = 10
     b = b * 2;
   }                         b = 20
}                                                              http://www.java2all.com
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.




                                                      http://www.java2all.com
Call By Reference




                    http://www.java2all.com
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.                                 http://www.java2all.com
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.
                                            http://www.java2all.com
public class CallBy_Reference
{
   public static void main(String[] args)
   {
              Reference r = new Reference(10,20);
              System.out.println("a and b before call............");
              System.out.println("a = "+r.a);
              System.out.println("b = "+r.b);
              r.call(r); // CALL BY REFERENCE
              System.out.println("a and b after call.............");
              System.out.println("a = "+r.a);
              System.out.println("b = "+r.b);
   }
}
class Reference               Output :
{
   int a,b;
   Reference(int i,int j)
   {
                              a and b before call............
     a=i;
     b = j;
                              a = 10
   }                          b = 20
   void call(Reference r)
   {                          a and b after call.............
     r.a = a * 2;
     r.b = b * 2;
                              a = 20
}
   }                          b = 40
                                                                       http://www.java2all.com
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.




                                           http://www.java2all.com
Recursion



            http://www.java2all.com
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.


                                             http://www.java2all.com
import java.util.Scanner;
class Factorial
{
    int fact(int n) // this is a recursive function
   {
      int result;
      if(n==1)
         return 1;
      result = fact(n-1) * n; //From here function call it self (fact(n-1))
      return result;
   }
}
public class Recursion
                                                                    Output :
{
   public static void main(String args[])
   {
                                                                    Enter int no = 7
      int x;                                                        Factorial of7 is 5040
      Scanner s = new Scanner(System.in);
      System.out.print("Enter int no = ");
      x = s.nextInt();
      Factorial f = new Factorial();
      System.out.println("Factorial of" + x + " is " + f.fact(x));
   }
}

                                                                                   http://www.java2all.com
•       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.


                                                 http://www.java2all.com
Nested Class



               http://www.java2all.com
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.

       If A is nesting class B, then A has access to all
the members of B, including private members. But
the B does not have access to the members of nested
class.                                         http://www.java2all.com
There are two types of nested classes:
1.   Static
2.   Non – Static

Static nested class :-

       A static nested class is one which has the
static modifier, as it is static it must access the
member of its enclosing class through an object.
That means it cannot refer to member of its
enclosing class directly.

                                               http://www.java2all.com
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.
                                              http://www.java2all.com
class Inner1
{
     class Contents
     {
          private int i = 16;
          public int value()
          {
              return i;
          }
     }
     class Destination
     {
          private String label;
          Destination(String whereTo)
          {
              label = whereTo;
          }
     }
     public void ship(String dest)
     {
          Contents c = new Contents(); // create object of inner class Contents
          Destination d = new Destination(dest); // create object of inner class Destination

         System.out.println("Shipped " + c.value() + " item(s) to " + dest);
    }
                                                                                       http://www.java2all.com
public static void main(String args[])
    {
          Inner1 p = new Inner1();
          p.ship("Congo"); //call ship method of outer class "inner1"
    }
}



Output :

Shipped 16 item(s) to Congo




                                                                        http://www.java2all.com
Let us see one more example but here the
program will not compile
class Outer
{
  int outer_x = 100;
  void test()
  {
     Inner inner = new Inner();
     inner.display();
  }
  class Inner // this is an inner class
  {
     int y = 10; // y is local to Inner
     void display()
     {
       System.out.println("display: outer_x = " + outer_x);
     }
  }
  void showy()
  {
     System.out.println(y); // error, y not known here!
  }
}
                                                              http://www.java2all.com
class InnerClassDemo
{
    public static void main(String args[])
  {
     Outer outer = new Outer();
     outer.test();
  }
}




        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( ).



                                               http://www.java2all.com
Command Line
  Argument


               http://www.java2all.com
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( ).
                                        http://www.java2all.com
Example :-
class CommandLine
{
  public static void main(String args[])
  {
     for(int i=0; i < args.length; i++)
       System.out.println("args[" + i + "]: " +args[i]);
  }
}
Try executing this program, as shown here:
java Command Line this is a test 100 -1
When you do, you will see the following output:

args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
                                                           http://www.java2all.com

More Related Content

PPTX
Java servlets
PPTX
Strings in Java
PPTX
Chapter 3 servlet & jsp
PPTX
Arrays in Java
PDF
Java IO
PPT
Iterator Design Pattern
PPTX
Java - Generic programming
PPT
Java Input Output and File Handling
Java servlets
Strings in Java
Chapter 3 servlet & jsp
Arrays in Java
Java IO
Iterator Design Pattern
Java - Generic programming
Java Input Output and File Handling

What's hot (20)

PPTX
Design Pattern - Factory Method Pattern
PPTX
Constructor ppt
PPS
String and string buffer
PPTX
SQL for pattern matching (Oracle 12c)
PPTX
Access Modifier.pptx
PPT
Introduction to ADO.NET
PPTX
constructors in java ppt
PPT
Programming loop
PDF
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
PPSX
Javascript variables and datatypes
PPTX
Inner classes in java
PPTX
Java string handling
PPTX
java memory management & gc
PPTX
Lecture_7-Encapsulation in Java.pptx
PPT
Java Collections Framework
PDF
07 java collection
PPT
Java operators
PPT
Serialization/deserialization
PPTX
Static keyword ppt
PDF
What is Socket Programming in Python | Edureka
Design Pattern - Factory Method Pattern
Constructor ppt
String and string buffer
SQL for pattern matching (Oracle 12c)
Access Modifier.pptx
Introduction to ADO.NET
constructors in java ppt
Programming loop
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
Javascript variables and datatypes
Inner classes in java
Java string handling
java memory management & gc
Lecture_7-Encapsulation in Java.pptx
Java Collections Framework
07 java collection
Java operators
Serialization/deserialization
Static keyword ppt
What is Socket Programming in Python | Edureka
Ad

Similar to Class method (20)

PPTX
Chap2 class,objects contd
PPT
Inheritance and-polymorphism
PDF
Java Class Design
PPT
Operator overloading
PPT
Pointcuts and Analysis
PDF
TypeScript Introduction
PDF
C++ aptitude
PPSX
C# 6.0 - April 2014 preview
PPTX
Basic java, java collection Framework and Date Time API
PPTX
How to add an optimization for C# to RyuJIT
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
PDF
Object Oriented Solved Practice Programs C++ Exams
PPTX
PVS-Studio team experience: checking various open source projects, or mistake...
DOCX
Java practical
PPTX
05. Java Loops Methods and Classes
DOCX
PDF
Simple 27 Java Program on basic java syntax
PPTX
Advanced JavaScript
PDF
Java programming lab manual
Chap2 class,objects contd
Inheritance and-polymorphism
Java Class Design
Operator overloading
Pointcuts and Analysis
TypeScript Introduction
C++ aptitude
C# 6.0 - April 2014 preview
Basic java, java collection Framework and Date Time API
How to add an optimization for C# to RyuJIT
Unit 1 Part - 3 constructor Overloading Static.ppt
Object Oriented Solved Practice Programs C++ Exams
PVS-Studio team experience: checking various open source projects, or mistake...
Java practical
05. Java Loops Methods and Classes
Simple 27 Java Program on basic java syntax
Advanced JavaScript
Java programming lab manual
Ad

More from kamal kotecha (20)

PPS
Java Hibernate Programming with Architecture Diagram and Example
PPTX
Network programming in java - PPT
PPT
Java servlet life cycle - methods ppt
PPS
Java rmi example program with code
PPS
Java rmi
PPS
Jdbc example program with access and MySql
PPS
Jdbc api
PPS
Jdbc architecture and driver types ppt
PPS
Java Exception handling
PPS
JSP Error handling
PPS
Jsp element
PPS
Jsp chapter 1
PPS
Wrapper class
PPS
Packages and inbuilt classes of java
PPS
Interface
PPS
Inheritance chepter 7
PPS
Introduction to class in java
PPS
Control statements
PPTX
Jsp myeclipse
PPTX
basic core java up to operator
Java Hibernate Programming with Architecture Diagram and Example
Network programming in java - PPT
Java servlet life cycle - methods ppt
Java rmi example program with code
Java rmi
Jdbc example program with access and MySql
Jdbc api
Jdbc architecture and driver types ppt
Java Exception handling
JSP Error handling
Jsp element
Jsp chapter 1
Wrapper class
Packages and inbuilt classes of java
Interface
Inheritance chepter 7
Introduction to class in java
Control statements
Jsp myeclipse
basic core java up to operator

Recently uploaded (20)

PDF
Bacterial Diversity and Evolution Bacterial Taxonomy Lecture (4)_.pdf
PPTX
CHF refers to the condition wherein heart unable to pump a sufficient amount ...
PDF
NGÂN HÀNG CÂU HỎI TÁCH CHỌN LỌC THEO CHUYÊN ĐỀ TỪ ĐỀ THI THỬ TN THPT 2025 TIẾ...
PDF
BÀI GIẢNG POWER POINT TIẾNG ANH 6 - I LEARN SMART WORLD - CẢ NĂM - NĂM 2025 (...
PDF
Global strategy and action plan on oral health 2023 - 2030.pdf
PPTX
macro complete discussion with given activities
PDF
BP303T PHARMACEUTICALMICROBIOLOGY UNIT 1
PPTX
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
PDF
gsas-cvs-and-cover-letters jhvgfcffttfghgvhg.pdf
PDF
Physical pharmaceutics two in b pharmacy
PPTX
Ppt obs emergecy.pptxydirnbduejguxjjdjidjdbuc
PDF
IDA Textbook Grade 10 .pdf download link if 1st link isn't working so hard to...
DOCX
OA 7- Administrative Office Procedure and Management.docx
PPTX
Power of Gratitude: Honouring our teachers
PPTX
Environmental Sciences and Sustainability Chapter 2
PPTX
INTRODUCTION TO PHILOSOPHY FULL SEM - COMPLETE.pptxINTRODUCTION TO PHILOSOPHY...
PDF
BA-1ST(Education)-Education and Society.pdf
PDF
17649-Learning By Doing_text-tailieu.pdf
PDF
V02-Session-4-Leadership-Through-Assessment-MLB.pdf
PDF
HSE and their team are going through the hazards of the issues with learning ...
Bacterial Diversity and Evolution Bacterial Taxonomy Lecture (4)_.pdf
CHF refers to the condition wherein heart unable to pump a sufficient amount ...
NGÂN HÀNG CÂU HỎI TÁCH CHỌN LỌC THEO CHUYÊN ĐỀ TỪ ĐỀ THI THỬ TN THPT 2025 TIẾ...
BÀI GIẢNG POWER POINT TIẾNG ANH 6 - I LEARN SMART WORLD - CẢ NĂM - NĂM 2025 (...
Global strategy and action plan on oral health 2023 - 2030.pdf
macro complete discussion with given activities
BP303T PHARMACEUTICALMICROBIOLOGY UNIT 1
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
gsas-cvs-and-cover-letters jhvgfcffttfghgvhg.pdf
Physical pharmaceutics two in b pharmacy
Ppt obs emergecy.pptxydirnbduejguxjjdjidjdbuc
IDA Textbook Grade 10 .pdf download link if 1st link isn't working so hard to...
OA 7- Administrative Office Procedure and Management.docx
Power of Gratitude: Honouring our teachers
Environmental Sciences and Sustainability Chapter 2
INTRODUCTION TO PHILOSOPHY FULL SEM - COMPLETE.pptxINTRODUCTION TO PHILOSOPHY...
BA-1ST(Education)-Education and Society.pdf
17649-Learning By Doing_text-tailieu.pdf
V02-Session-4-Leadership-Through-Assessment-MLB.pdf
HSE and their team are going through the hazards of the issues with learning ...

Class method

  • 1. Chapter 6 Classes And Method http://www.java2all.com
  • 2. Method Overloading http://www.java2all.com
  • 3. 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. http://www.java2all.com
  • 4. 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. http://www.java2all.com
  • 5. 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. http://www.java2all.com
  • 6. public class MethodOver { int n1; int n2; MethodOver() { n1 = 10; n2 = 20; } void square() { System.out.println("The Square is " + n1 * n2); } void square(int p1) { n1 = p1; System.out.println("The Square is " + n1 * n2); } void square(int p1, int p2) { n1 = p1; n2 = p2; System.out.println("The Square is " + n1 * n2); } public static void main(String args[]) { MethodOver obj1 = new MethodOver(); obj1.square(); //call non parameterise method obj1.square(4); //call method which has 1 argument obj1.square(7,8); //call method which has 2 argument } http://www.java2all.com
  • 7. public class MethodOver { int n1; int n2; MethodOver() { n1 = 10; n2 = 20; } void square() { System.out.println("The Square is " + n1 * n2); } Output : void square(int p1) { n1 = p1; System.out.println("The Square is " + n1 * n2); } The Square is 200 void square(int p1, int p2) { The Square is 80 n1 = p1; The Square is 56 n2 = p2; System.out.println("The Square is " + n1 * n2); } You can see that here we have 3 square public static void main(String args[]) { methods with different argument. MethodOver obj1 = new MethodOver(); Its called method overloading. obj1.square(); //call non parameterise method obj1.square(4); //call method which has 1 argument obj1.square(7,8); //call method which has 2 argument } http://www.java2all.com
  • 8. Constructors overloading http://www.java2all.com
  • 9. Constructors Along with method overloading, we can also overload constructors. Constructors having the same name with different parameter list is called constructor overloading. http://www.java2all.com
  • 10. class Point { int x; int y; Point(int a, int b) { x = a; y = b; } } class Circle { int originX; int originY; int radius; //Default Constructor Circle() { originX = 5; originY = 5; radius = 3; } // Constructor initializing the coordinates of origin and the radius. http://www.java2all.com
  • 11. Circle(int x1, int y1, int r) { originX = x1; originY = y1; radius = r; } Circle(Point p, int r) { originX = p.x; originY = p.y; radius = r; } void display() { System.out.println("--Center at " + originX + " and " + originY); System.out.println("Radius = " + radius); } public static void main(String args[]) { Circle c1 = new Circle(); Circle c2 = new Circle(10,20,5); Circle c3 = new Circle(new Point(15,25),10); c1.display(); c2.display(); c3.display(); } } http://www.java2all.com
  • 12. Circle(int x1, int y1, int r) { originX = x1; originY = y1; radius = r; } Circle(Point p, int r) { originX = p.x; originY = p.y; radius = r; } void display() { Output : --Center at 5 and 5 System.out.println("--Center at " + originX + " and " + originY); System.out.println("Radius = " + radius); } Radius = 3 public static void main(String args[]) { --Center at 10 and 20 Circle c1 = new Circle(); = 5 Radius --Center at 15 and 25 Circle c2 = new Circle(10,20,5); Circle c3 = new Circle(new Point(15,25),10); c1.display(); Radius = 10 c2.display(); c3.display(); } } http://www.java2all.com
  • 13. Above program is quite complicated here i am giving you perfect flow of program. First of all note one thing that newClassName() 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 Circle c1 = new Circle(); non parameterize constructor will be called for object c1 so we get output like Center at 5 and 5 Radius = 3 in c1.display(). http://www.java2all.com
  • 14. 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 Center 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 Center at 15 and 25 Radius = 10 in c3.display(). http://www.java2all.com
  • 15. More About Method http://www.java2all.com
  • 16. 1. Passing Objects as a Parameter to Method. 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. http://www.java2all.com
  • 17. class PassObj { int n1; int n2; PassObj() // constructor { n1 = 0; n2 = 0; } PassObj(int p1, int p2) Output : { n1 = p1; n2 = p2; Multiplication is } void multiply(PassObj p1) 30 { int temp; temp = p1.n1 * p1.n2; System.out.println("Multiplication is " + temp); } public static void main(String args[]) { PassObj obj1 = new PassObj(5,6); PassObj obj2 = new PassObj(); obj2.multiply(obj1); } } http://www.java2all.com
  • 18. 2. Method overloading with object as a parameter class MetObjOv { int n1; int n2; // constructor MetObjOv() { n1 = 0; n2 = 0; } MetObjOv(int x, int y) { n1 = x; n2 = y; } void multiply(MetObjOv p1) { n1 = p1.n1; n2 = p1.n2; System.out.println("There is nothing to multiply "); System.out.println("n1 = "+n1+"tn2 = " +n2); } http://www.java2all.com
  • 19. void multiply(MetObjOv p1, MetObjOv p2) { n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2; System.out.println("Multiplication of two objects "); System.out.println("n1 = " + n1 + "tn2 = " + n2 ); } public static void main(String args[]) { MetObjOv obj1 = new MetObjOv(5,6); MetObjOv obj2 = new MetObjOv(6,5); MetObjOv obj3 = new MetObjOv(); obj3.multiply(obj1); obj3.multiply(obj1, obj2); } } Output : There is nothing to multiply n1 = 5 n2 = 6 Multiplication of two objects n1 = 30 n2 = 30 http://www.java2all.com
  • 20. 3. Return an Object. A method can return any type of data, including class type (object) that you create. http://www.java2all.com
  • 21. class RetObj { int n1; int n2; // constructor RetObj() { n1 = 0; n2 = 0; } RetObj(int x, int y) { n1 = x; n2 = y; } RetObj multiply(RetObj p1, RetObj p2) { n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2; return (this); } void display() { System.out.println("An Example of returning an Object "); System.out.println("n1 = "+n1+"tn2 = " +n2); } http://www.java2all.com
  • 22. public static void main(String args[]) { RetObj obj1 = new RetObj(5,6); RetObj obj2 = new RetObj(6,5); RetObj obj3 = new RetObj(); obj3 = obj3.multiply(obj1, obj2); obj3.display(); } } Output : An Example of returning an Object n1 = 30 n2 = 30 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. http://www.java2all.com
  • 23. Call By Value http://www.java2all.com
  • 24. 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. http://www.java2all.com
  • 25. 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. http://www.java2all.com
  • 26. public class CallBy_Value { public static void main(String[] args) { Value v = new Value(10,20); System.out.println("a and b before call............"); System.out.println("a = "+v.a); System.out.println("b = "+v.b); v.call(v.a,v.b); // CALL BY VALUE System.out.println("a and b after call............"); System.out.println("a = "+v.a); System.out.println("b = "+v.b); } } class Value Output : { int a,b; Value(int i,int j) a and b before call............ { a=i; a = 10 b = j; } b = 20 void call(int a, int b) { a and b after call............ a = a * 2; a = 10 b = b * 2; } b = 20 } http://www.java2all.com
  • 27. 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. http://www.java2all.com
  • 28. Call By Reference http://www.java2all.com
  • 29. 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. http://www.java2all.com
  • 30. 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. http://www.java2all.com
  • 31. public class CallBy_Reference { public static void main(String[] args) { Reference r = new Reference(10,20); System.out.println("a and b before call............"); System.out.println("a = "+r.a); System.out.println("b = "+r.b); r.call(r); // CALL BY REFERENCE System.out.println("a and b after call............."); System.out.println("a = "+r.a); System.out.println("b = "+r.b); } } class Reference Output : { int a,b; Reference(int i,int j) { a and b before call............ a=i; b = j; a = 10 } b = 20 void call(Reference r) { a and b after call............. r.a = a * 2; r.b = b * 2; a = 20 } } b = 40 http://www.java2all.com
  • 32. 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. http://www.java2all.com
  • 33. Recursion http://www.java2all.com
  • 34. 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. http://www.java2all.com
  • 35. import java.util.Scanner; class Factorial { int fact(int n) // this is a recursive function { int result; if(n==1) return 1; result = fact(n-1) * n; //From here function call it self (fact(n-1)) return result; } } public class Recursion Output : { public static void main(String args[]) { Enter int no = 7 int x; Factorial of7 is 5040 Scanner s = new Scanner(System.in); System.out.print("Enter int no = "); x = s.nextInt(); Factorial f = new Factorial(); System.out.println("Factorial of" + x + " is " + f.fact(x)); } } http://www.java2all.com
  • 36. 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. http://www.java2all.com
  • 37. Nested Class http://www.java2all.com
  • 38. 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. If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class. http://www.java2all.com
  • 39. There are two types of nested classes: 1. Static 2. Non – Static Static nested class :- A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object. That means it cannot refer to member of its enclosing class directly. http://www.java2all.com
  • 40. 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. http://www.java2all.com
  • 41. class Inner1 { class Contents { private int i = 16; public int value() { return i; } } class Destination { private String label; Destination(String whereTo) { label = whereTo; } } public void ship(String dest) { Contents c = new Contents(); // create object of inner class Contents Destination d = new Destination(dest); // create object of inner class Destination System.out.println("Shipped " + c.value() + " item(s) to " + dest); } http://www.java2all.com
  • 42. public static void main(String args[]) { Inner1 p = new Inner1(); p.ship("Congo"); //call ship method of outer class "inner1" } } Output : Shipped 16 item(s) to Congo http://www.java2all.com
  • 43. Let us see one more example but here the program will not compile class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } class Inner // this is an inner class { int y = 10; // y is local to Inner void display() { System.out.println("display: outer_x = " + outer_x); } } void showy() { System.out.println(y); // error, y not known here! } } http://www.java2all.com
  • 44. class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } 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( ). http://www.java2all.com
  • 45. Command Line Argument http://www.java2all.com
  • 46. 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( ). http://www.java2all.com
  • 47. Example :- class CommandLine { public static void main(String args[]) { for(int i=0; i < args.length; i++) System.out.println("args[" + i + "]: " +args[i]); } } Try executing this program, as shown here: java Command Line this is a test 100 -1 When you do, you will see the following output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1 http://www.java2all.com

Editor's Notes

  • #17: White Space Characters
  • #18: White Space Characters
  • #19: White Space Characters
  • #25: White Space Characters
  • #30: White Space Characters
  • #31: White Space Characters
  • #33: White Space Characters
  • #41: White Space Characters
  • #42: White Space Characters