classes&methods in java

Upload: sheeba-dhuruvaraj

Post on 02-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Classes&Methods in java

    1/42

    CLASSES& METHODS

  • 7/27/2019 Classes&Methods in java

    2/42

    CLASSESThe general form of a class definition is shown here:

    class ClassName {

    type instance-variable1;

    type instance-variable2;

    // ...

    type instance-variableN;

    type methodName1(parameter-list) {// body of method

    }

    type methodName2(parameter-list) {

    // body of method

    }// ...

    type methodNameN(parameter-list) {

    // body of method

    }

    }2

  • 7/27/2019 Classes&Methods in java

    3/42

    The data, or variables, defined within a

    class are calledins tance variab les.

    The code is contained within methods.

    Collectively, the methods and variables

    defined within a class are called

    membersof the class. Example:class Vehicle {

    int passengers; // number of passengersint fuelcap; // fuel capacity in gallons

    int mpg;//fuel consumption in miles per gallon

    }

    3

  • 7/27/2019 Classes&Methods in java

    4/42

    Creating Object

    Vehicle minivan = new Vehicle(); /*create a Vehicle object called minivan*/

    minivan.fuelcap= 16; /* Accessing themember of the Vehicle class */

    (or)

    Vehicle minivan; /* declare reference to

    object */minivan = new Vehicle(); /* allocate aVehicle object */

    4

  • 7/27/2019 Classes&Methods in java

    5/42

    Examples

    // This program creates two Vehicle objects.

    class Vehicle {

    int passengers;

    int fuelcap;

    int mpg;}

    class VehicleDemo {public static void main(String args[]) {

    Vehicle minivan = new Vehicle();

    Vehicle sportscar = new Vehicle();

    int range1, range2;// assign values to fields in minivan

    minivan.passengers = 7;

    minivan.fuelcap = 16;

    minivan.mpg = 21;5

  • 7/27/2019 Classes&Methods in java

    6/42

    // assign values to fields in sportscar

    sportscar.passengers = 2;

    sportscar.fuelcap = 14;

    sportscar.mpg = 12;

    // compute the ranges assuming a full tank of gas

    range1 = minivan.fuelcap * minivan.mpg;

    range2 = sportscar.fuelcap * sportscar.mpg;

    System.out.println("Minivan can carry " +

    minivan.passengers +" with a range of " +range1);

    System.out.println("Sportscar can carry " +sportscar.passengers +

    " with a range of " + range2);

    }

    }

    Output:

    Minivan can carry 7 with a range of 336

    Sportscar can carry 2 with a range of 1686

  • 7/27/2019 Classes&Methods in java

    7/42

    Adding a Method// Add range to Vehicle.

    class Vehicle {

    int passengers; // number of passengers

    int fuelcap; // fuel capacity in gallons

    int mpg; // fuel consumption in miles per gallon

    // Display the range.

    void range() {

    System.out.println("Range is " + fuelcap * mpg);

    }

    }

    class AddMeth {public static void main(String args[]) {

    Vehicle minivan = new Vehicle();

    Vehicle sportscar = new Vehicle();

    7

  • 7/27/2019 Classes&Methods in java

    8/42

    // assign values to fields in minivan

    minivan.passengers = 7;

    minivan.fuelcap = 16;

    minivan.mpg = 21;

    // assign values to fields in sportscar

    sportscar.passengers = 2;

    sportscar.fuelcap = 14;

    sportscar.mpg = 12;System.out.print("Minivan can carry " +

    minivan.passengers +". ");

    minivan.range(); // display range of minivan

    System.out.print("Sportscar can carry " +sportscar.passengers +". ");

    sportscar.range(); // display range of sportscar.

    }

    }

    8

  • 7/27/2019 Classes&Methods in java

    9/42

    Constructors

    A constructor initializes an objectimmediately upon creation.

    It has the same name as the class in which it

    resides and is syntactically similar to amethod.

    Constructors have no return type, not even

    void. The constructors job to initialize the internal

    state of an object so that the code creating

    an instance will have a fully initialized,

    usable object immediately. 9

  • 7/27/2019 Classes&Methods in java

    10/42

    Example// Add a constructor.

    class Vehicle {

    int passengers; // number of passengers

    int fuelcap; // fuel capacity in gallons

    int mpg; // fuel consumption in miles per gallon

    // This is a constructor for Vehicle.

    Vehicle(int p, int f, int m) {

    passengers = p;

    fuelcap = f;

    mpg = m;

    }// Return the range.

    int range() {

    return mpg * fuelcap;

    }10

  • 7/27/2019 Classes&Methods in java

    11/42

    // Compute fuel needed for a given distance.

    double fuelneeded(int miles) {

    return (double) miles / mpg;

    }

    }class VehConsDemo {

    public static void main(String args[]) {

    // construct complete vehicles

    Vehicle minivan = new Vehicle(7, 16, 21);

    Vehicle sportscar = new Vehicle(2, 14, 12);

    double gallons;

    int dist = 252;

    gallons = minivan.fuelneeded(dist);

    System.out.println("To go " + dist + " miles minivanneeds " +gallons + " gallons of fuel.");

    gallons = sportscar.fuelneeded(dist);

    System.out.println("To go " + dist + " miles sportscarneeds " +gallons + " gallons of fuel.");

    }

    } 11

  • 7/27/2019 Classes&Methods in java

    12/42

    The this Keyword

    this can be used inside any method to

    refer to the current object.

    That is, this is always a reference to

    the object on which the method was

    invoked.Vehicle(int p, int f, int m) {

    this.passengers = p;this.fuelcap = f;

    this.mpg = m;

    }

    12

  • 7/27/2019 Classes&Methods in java

    13/42

    Garbage Collection

    In some languages, such as C++,dynamically allocated objects must be

    manually released by use of a delete

    operator.

    Java takes a different approach; it

    handles de-allocation for you

    automatically. The technique that

    accomplishes this is called garbage

    col lect ion.

    13

  • 7/27/2019 Classes&Methods in java

    14/42

    The finalize( ) Method Sometimes an object will need to

    perform some action when it isdestroyed.

    To handle such situations, Java provides

    a mechanism called f inal izat ion. To add a finalizer to a class, you simply

    define the finalize( ) method.

    The finalize( ) method has this generalform:protected void finalize( )

    {

    // finalization code here 14

  • 7/27/2019 Classes&Methods in java

    15/42

    Overloading Methods

    In Java it is possible to define two ormore methods within the same class

    that share the same name, as long as

    their parameter declarations aredifferent.

    When an overloaded method is invoked,

    Java uses the type and/or number ofarguments as its guide to determine

    which version of the overloaded method

    to actually call.15

  • 7/27/2019 Classes&Methods in java

    16/42

    Exampleclass OverloadDemo {

    void test() {

    System.out.println("No parameters");

    }

    // Overload test for one integer parameter.

    void test(int a) {System.out.println("a: " + a);

    }

    //Overload test for two integer parameters.

    void test(int a, int b) {System.out.println("a and b: "+a+" " + b);

    }

    16

  • 7/27/2019 Classes&Methods in java

    17/42

    // overload test for a double parameter

    double test(double a) {

    System.out.println("double a: " + a);

    return a*a;

    }

    }

    class Overload {

    public static void main(String args[]) {

    OverloadDemo ob = new OverloadDemo();double result;

    // call all versions of test()

    ob.test();

    ob.test(10);

    ob.test(10, 20);

    result = ob.test(123.25);

    System.out.println("Result of ob.test(123.25): "+ result);

    }

    } 17

  • 7/27/2019 Classes&Methods in java

    18/42

    Overloading Constructorsclass MyClass {

    int x;

    MyClass() {

    System.out.println("Inside MyClass().");

    x = 0;

    }

    MyClass(int i) {System.out.println("Inside MyClass(int).");

    x = i;

    }

    MyClass(double d) {System.out.println("Inside MyClass(double).");

    x = (int) d;

    }

    MyClass(int i, int j) {

    System.out.println("Inside MyClass(int, int)."); 18

  • 7/27/2019 Classes&Methods in java

    19/42

    x = i * j;

    }

    }class OverloadConsDemo {

    public static void main(String args[]) {

    MyClass t1 = new MyClass();

    MyClass t2 = new MyClass(88);

    MyClass t3 = new MyClass(17.23);

    MyClass t4 = new MyClass(2, 4);

    System.out.println("t1.x: " + t1.x);

    System.out.println("t2.x: " + t2.x);

    System.out.println("t3.x: " + t3.x);

    System.out.println("t4.x: " + t4.x);

    }

    }

    19

    P i Obj

  • 7/27/2019 Classes&Methods in java

    20/42

    Passing Objects as

    Parameters

    // Objects may be passed to methods.class Test {

    int a, b;

    Test(int i, int j) {

    a = i;

    b = j;

    }

    /* return true if o is equal to the invokingobject */

    boolean equals(Test o) {if(o.a == a && o.b == b) return true;

    else return false;

    }

    } 20

  • 7/27/2019 Classes&Methods in java

    21/42

    class PassOb {public static void main(String args[]) {

    Test ob1 = new Test(100, 22);

    Test ob2 = new Test(100, 22);

    Test ob3 = new Test(-1, -1);System.out.println("ob1==ob2:"+ob1.equals(ob2));

    System.out.println("ob1==ob3:"+ob1.equals(ob3));

    }

    }

    21

  • 7/27/2019 Classes&Methods in java

    22/42

    Returning Objects

    // Returning an object.

    class Test {

    int a;

    Test(int i) {

    a = i;

    }

    Test incrByTen() {

    Test temp = new Test(a+10);

    return temp;}

    }

    22

  • 7/27/2019 Classes&Methods in java

    23/42

    class RetOb {public static void main(String args[]) {

    Test ob1 = new Test(2);

    Test ob2;

    ob2 = ob1.incrByTen();System.out.println("ob1.a: " + ob1.a);

    System.out.println("ob2.a: " + ob2.a);

    ob2 = ob2.incrByTen();

    System.out.println("ob2.a after second increase:"+ob2.a);

    }

    }

    23

  • 7/27/2019 Classes&Methods in java

    24/42

    Access Specifiers

    /* This program demonstrates the difference

    between public and private. */class Test {

    int a; // default access

    public int b; // public access

    private int c; // private access// methods to access c

    void setc(int i) { // set c's value

    c = i;

    }

    int getc() { // get c's value

    return c;

    }

    }

    24

  • 7/27/2019 Classes&Methods in java

    25/42

    class AccessTest {

    public static void main(String args[]) {

    Test ob = new Test();

    /* These are OK, a and b may be accesseddirectly */

    ob.a = 10;

    ob.b = 20;// This is not OK and will cause an error

    // ob.c = 100; // Error!

    // You must access c through its methods

    ob.setc(100); // OKSystem.out.println("a, b, and c: " + ob.a + " "+ ob.b + " " + ob.getc());

    }

    }

    25

  • 7/27/2019 Classes&Methods in java

    26/42

    static Keywordclass StaticDemo {

    int x; // a normal instance variablestatic int y; // a static variable

    }

    class SDemo {

    public static void main(String args[]) {StaticDemo ob1 = new StaticDemo();

    StaticDemo ob2 = new StaticDemo();

    ob1.x = 10;

    ob2.x = 20;

    System.out.println("Of course, ob1.x and ob2.x " +

    "are independent.");

    System.out.println("ob1.x: " + ob1.x +

    "\nob2.x: " + ob2.x);

    26

  • 7/27/2019 Classes&Methods in java

    27/42

    /* Each object shares one copy of

    a static variable. */

    System.out.println("The static variable y isshared.");

    ob1.y = 19;

    System.out.println("ob1.y: " + ob1.y + "\nob2.y:" + ob2.y);

    System.out.println("The static variable y can be"+ " accessed through its class.");

    StaticDemo.y = 11; /* Can refer to y throughclass name */

    System.out.println("StaticDemo.y: " +

    StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: "+ ob2.y);

    }

    }

    27

  • 7/27/2019 Classes&Methods in java

    28/42

    static Block

    // Use a static blockclass StaticBlock {

    static double rootOf2;

    static double rootOf3;

    static {System.out.println("Inside static block.");

    rootOf2 = Math.sqrt(2.0);

    rootOf3 = Math.sqrt(3.0);

    }

    StaticBlock(String msg) {

    System.out.println(msg);

    }

    }

    28

  • 7/27/2019 Classes&Methods in java

    29/42

    class SBDemo {public static void main(String args[]) {

    StaticBlock ob = new staticBlock("InsideConstructor");

    System.out.println("Square root of 2 is "+ StaticBlock.rootOf2);

    System.out.println("Square root of 3 is "+ StaticBlock.rootOf3);

    }

    }

    29

  • 7/27/2019 Classes&Methods in java

    30/42

    final Variables

    It prevents modifying the value.

    It must be initialized.

    Choose all uppercase identifiers.

    Do not occupy memory on a per-instance basis.

    The keyword final can also be applied

    to methods.final int FILE_NEW = 1;

    final int FILE_OPEN = 2;

    final int FILE_SAVE = 3;

    final int FILE_SAVEAS = 4;

    final int FILE_QUIT = 5; 30

  • 7/27/2019 Classes&Methods in java

    31/42

    Array Variables

    Declaration type var-name[ ]; //E.g: int arr[ ];

    Memory Allocation

    array-var= new type[size]; // arr=new

    int[5];

    Types:

    Single and Multi-Dimensional Array

    Jagged Array- Different column sized

    array

    Alternative Array Declaration

    int a[ ] = new int[5]; 31

  • 7/27/2019 Classes&Methods in java

    32/42

    class JArray {public static void main(Stringargs[]) {

    int twoD[][] = new int[4][];

    twoD[0] = new int[1];

    twoD[1] = new int[2];

    twoD[2] = new int[3];

    twoD[3] = new int[4];

    int i, j, k = 0;

    for(i=0; i

  • 7/27/2019 Classes&Methods in java

    33/42

    twoD[i][j] = k;k++;

    }

    for(i=0; i

  • 7/27/2019 Classes&Methods in java

    34/42

    Example-2

    // To find the length of array member.class Length {

    public static void main(String args[]) {

    int a1[] = new int[10];

    int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};int a3[] = {4, 3, 2, 1};

    System.out.println("length of a1 is " + a1.length);

    System.out.println("length of a2 is " + a2.length);

    System.out.println("length of a3 is " + a3.length);

    }

    }

    34

  • 7/27/2019 Classes&Methods in java

    35/42

    Nested and Inner Classes

    It is possible to define a class within another

    class; such classes are known as nestedclasses.

    There are two types of nested classes: static

    and non-static.A static nested class is one which has the static

    modifier applied.

    An inner class is a non-static nested class.

    It has access to all of the variables and methods

    of its outer class and may refer to them directly

    in the same way that other non-static members

    of the outer class do 35

    class Outer {

  • 7/27/2019 Classes&Methods in java

    36/42

    int outer_x = 100;

    void test() {

    Inner inner = new Inner();

    inner.display();

    }

    // this is an inner class

    class Inner {

    void display() {

    System.out.println("display: outer_x = " + outer_x);}

    }

    }

    class InnerClassDemo {

    public static void main(String args[]) {Outer outer = new Outer();

    outer.test();

    }

    }

    36

  • 7/27/2019 Classes&Methods in java

    37/42

    String Class

    Stringis probably the most commonly

    used class in Javas class library.

    Every string that created is actually an

    object of type String.

    Even string constants are actually

    Stringobjects.String myString = "this is a test";

    Java defines one operator for String

    objects: +.

    String myString = "I" + " like " + "Java."; 37

  • 7/27/2019 Classes&Methods in java

    38/42

    Example

    class StrDemo {

    public static void main(String args[]) {

    String strOb1 = "First String";

    String strOb2 = "Second String";String strOb3 = strOb1+" and "+strOb2;

    System.out.println(strOb1);

    System.out.println(strOb2);

    System.out.println(strOb3);

    }

    }

    38

  • 7/27/2019 Classes&Methods in java

    39/42

    Some methods in String Class

    boolean equals(String object)

    Compares two given string objects.

    int length( )Gives the length of the

    given string. char charAt(int index)Gives the

    char at the given index.

    39

    class StringDemo2 {

  • 7/27/2019 Classes&Methods in java

    40/42

    public static void main(String args[]) {

    String strOb1 = "First String";

    String strOb2 = "Second String";

    String strOb3 = strOb1;

    System.out.println("Length of strOb1: " +

    strOb1.length());

    System.out.println("Char at index 3 instrOb1:" + strOb1.charAt(3));

    if(strOb1.equals(strOb2))

    System.out.println("strOb1 == strOb2");

    else

    System.out.println("strOb1 != strOb2");

    if(strOb1.equals(strOb3))

    System.out.println("strOb1 == strOb3");else

    System.out.println("strOb1 != strOb3");

    }

    }

    40

    Using Command Line Arguments

  • 7/27/2019 Classes&Methods in java

    41/42

    Using Command-Line Arguments

    A command-line argument is the information that

    directly follows the programs name on the commandline when it is executed.

    They are stored as strings in the String array passed tomain( ).

    Example:

    class CommandLine {public static void main(String args[]) {

    for(int i=0; i

  • 7/27/2019 Classes&Methods in java

    42/42

    Example

    class CLDemo{public static void main(String arg[]){

    int a[]=new int[arg.length];

    int sum=0;

    for(int i=0;i