SlideShare a Scribd company logo
1 of 47
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

What's hot (20)

Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java constructors
Java constructorsJava constructors
Java constructors
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
OOP Assignment 03.pdf
OOP Assignment 03.pdfOOP Assignment 03.pdf
OOP Assignment 03.pdf
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java package
Java packageJava package
Java package
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Interface in java
Interface in javaInterface in java
Interface in java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 

Similar to Class method

Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphismUsama Malik
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 

Similar to Class method (20)

Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
 
V8
V8V8
V8
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Java practical
Java practicalJava practical
Java practical
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java programs
Java programsJava programs
Java programs
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 

More from kamal kotecha

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 

More from kamal kotecha (19)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Recently uploaded

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

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

  1. White Space Characters
  2. White Space Characters
  3. White Space Characters
  4. White Space Characters
  5. White Space Characters
  6. White Space Characters
  7. White Space Characters
  8. White Space Characters
  9. White Space Characters