Monday 25 June 2012

JAVA -methods and keyword "this" and "super"


Methods :

 Wikipedia says "Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance."  
So one thing is clear , during compilation the variables get set and  during run time the methods act on the variables of these instances . (Not sure)

Similar to variables we have 2 types
1) instance methods
2) class methods

Definitions are same as we saw in variables section .

Lets concentrate on which can access which ?

http://docs.oracle.com says

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Lets not mug this up . Lets go by logic .

Instance methods are Object specific . so it can access that which are specific to instances(i.e., instance variables and methods ) and also those class methods and class variables which are common to all objects (as it knows which class's instance it is)
Class methods in not instance specific , it is common to all objects(or instances) , so it has no knowledge about the instance , as it is not instance specific . As it is totally unaware of the instances , it cannot access , instance variables and instance methods (which are instance specific) . Whereas it can access class methods and class variables .

So the keyword "this" is meaningless when used inside class methods .

Other classification
wikipedia gave three methods 

Abstract methods

An abstract method is one with only a signature and no implementation body. It is often used to specify that a subclass must provide an implementation of the method. Abstract methods are used to specify interfaces in some computer languages.[3]

[edit]Example

The following java code shows an abstract class that need to be extended:
abstract class Main{
 
        abstract int rectangle(int h,int w); //abstract method signature
}
The following subclass extends the main class:
public class Main2 extends Main{
 
        @Override
        int rectangle(int h,int w)
        {
                return h*w;
        }
 
}

Overloaded methods

http://java67.blogspot.in/2012/08/what-is-method-overriding-in-java-example-tutorial.html 
Overloaded methods are those with the same name but different formal parameters or return value type, if the language supports overloading on return type.[4] For example in the following C++, class geometry have two method named "area". But there parameter list is different which distinguish the methods. Many other languages provide this feature.
#include<iostream>
using namespace std;
class geometry
{
        public:
        static double area(double h,double w)
        {
                return h*w;
        }
        static double area(double r)
        {
                return r*r*3.14;
        }
 
};
int main()
{
        double rectangle_area=geometry().area(3,4);
        double circle_area=geometry().area(5);
        cout<<rectangle_area<<endl;
        cout<<circle_area<<endl;
        return 0;
}

[edit]Overridden methods

Overridden methods are those that are redefined in a subclass and hide methods of a superclass. It often creates confusion with overloaded methods. The main difference is overridden method is situated in a different class derived from a super class, while in case of overloaded method both methods can be in the same class. [5] Look at following example in java:
public class class1
{
        int f(int x)
        {
                return x+3;
        }
}
 
public class class2 extends class1
{
        @Override
        int f(int x) //overriding
        {
                return x*x;
        }
        int f(int x,int y) //overloading
        {
                return x*y;
        }
}

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.[2] Some languages allow a programmer to prevent a method from being overridden.

THIS :

For explanation on "this" refer the link below 

Inaddition read this 

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.

Also refer 
Using "this" to return the instance that is using the class 


SUPER :

1) Used to call methods in superclass without the object name so no instantiation is needed to call super class's method .You may ask me question why we need this , when we can call using the object name.. Answer is this :this gives facility to access methods of super class from being inside child class .


public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod(); // calls the parent classes method printMethod
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    //calls the child classes method printMethod 
    }
}

2) Used to invoke superclass's constructor . .You may ask me that we already have this my using "this".
Ya , this calls constructor from inside the class whose constructor is called and not from outside the class .


The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example thatMountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:
public MountainBike(int startHeight, 
                    int startCadence,
                    int startSpeed,
                    int startGear) {
    super(startCadence, startSpeed, startGear);
    seatHeight = startHeight;
}   
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();  
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.




No comments:

Post a Comment