IITDU Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Java Tutorial: Using Two Java Reference Keywords, this and super

2 posters

Go down

Java Java Tutorial: Using Two Java Reference Keywords, this and super

Post by BIT0102-Mohaimin Mon Sep 13, 2010 2:29 pm

The tutorial assumes that you have idea about the data structure stack. In case you do not have, the wiki article may help you. However, understanding how the methods work is not that necessary, just concentrate our point of focus, this and super.

this


Note: The word "this" is used as the key word in all the cases in the current section so that you do not get confused.

this is one of the most widely used key words in Java (Also available in some other object oriented languages, eg. C++). It is the reference to the current class. The following program demonstrates the use of this.

Here we have created a fixed length stack. Please note that, the package java.util provides a very flexible Stack. Still we are creating a stack here because I found it to be a good example for demonstrating this
Code:

public class ThisStack {
   protected int[]   array;
   protected int   top;

   public ThisStack(int[] array, int size) {
      if (size < array.length) {
         System.err.println("Stack overflow, can not initialize");
         return;
      }

      this.array = new int[size];
      /*
       * Perhaps the most common use of this. When a
       * function's parameter name matches with a field
       * name (very common in case of setters and
       * constructors), the field is referred by this.
       * Here the left side "array" is the field and right
       * one is the parameter. Referring using this is
       * called "qualifying". If not qualified, Java will
       * assume that you are referring the local variable.
       */

      for (int i = 0; i < array.length; i++) {
         this.array[i] = array[i];
      }

      this.top = size - 1;

      /*
    * You can qualify a member even if there is no local
    * variables with same name. Although it is unnecessary,
    * some programmers prefer the use. Here qualifying
    * "top" has no effect at all. But qualifying "array"
    * was necessary.
    */
      System.out.println("Constructor 1 (this) called...");
      System.out.println(getClass().getSimpleName()
            + " is created, array size: " + size + " initialized by "
            + (top + 1) + " values");
   }

   /*
    * In a constructor, you can
    * call another constructor of the class by using this.
    * Please note carefully that, constructor call must be
    * the first statement of a constructor. If you do
    * something else before calling constructor, the code
    * will not be compiled.
    */
   public ThisStack(int[] array) {
      this(array, array.length);
      /*
       * Here, the constructor we saw above is called. So
       * we need not write the codes we already wrote.
       * When a class has many constructors, the most
       * general one (I mean, with most number of
       * parameters) is implemented directly. Others
       * simply call another constructor with some default
       * values.
       */

      System.out.println("Constructor 2 (this) called...");
   }

   /*
    * Be careful about passing null as default value to
    * call a constructor with this. It may cause
    * NullPointerException.
    */
   public ThisStack(int size) {
      /*
       * May be you thought off calling this(null, size).
       * It would cause NullPointerException. Find out the
       * line number where it could happen.
       */
      array = new int[size];
      top = -1;

      System.out.println("Constructor 3 (this) called...");
      System.out.println(getClass().getSimpleName()
            + " is created, array size: " + size + " initialized by "
            + (top + 1) + " values");
   }

   public void push(int value) {
      if (top == array.length - 1) {
         System.err.println("Stack overflow, can not add more elements.");
         return;
      }

      array[++top] = value;
   }

   public int pop() {
      if (top == -1) {
         System.err.println("Stack underflow, no elements available to pop");
         return 0;
      }

      return array[top--];
   }

   /*
    * You can call a method of current class using this. It
    * is useful when the current class inherits another
    * class and overload a method. We will discuss that
    * in the section about super.
    */
   public int[] pop(int popsize) {
      int popped[] = new int[popsize];
      for (int i = 0; i < popped.length; i++) {
         popped[i] = this.pop();
         /*
          * Here, the use of this is unnecessary.
          */
      }

      return popped;
   }

   /*
    * Java always treats the most local member as the
    * default one. We have already seen this in the comment
    * about qualifying. We will see again. Here is an
    * inner class that also has a variable named "top".
    * Lets see how this behaves here.
    */

   /*
    * The inner class bellow is irrelevant to the program.
    * It is created only for demonstration purpose.
    */
   class Inner {
      int   top;

      public Inner() {
         this.top = 5;
         top = 6;
         /*
          * You are trapped. There is no way to refer the
          * outer class's "top". Both the statement
          * refers the inner top.
          */

         top = array.length;
         /*
          * The statement is valid. As there is no
          * variable named array in the inner class,
          * "array" simply refers the outer class's
          * "array"
          */

         // top = this.array.length;
         /*
          * The commented line is an error. this is
          * reference to the class Inner, which has no
          * member named "array"
          */
      }
   }
}


super


super is related to inheritance so I assume that you are familiar with (at least) basic inheritance.

super is used to refer the parent class members of a child class.
The following example implements a dynamic-length stack that inherits ThisStack.
Code:

import java.util.Arrays;

public class SuperStack extends ThisStack {
   private int   expandBy;

   public SuperStack(int[] array, int initialSize, int expandBy) {
      super(array, initialSize);
      /*
       * Calling the super class's constructor. You need
       * not implement those you have already implemented.
       * In fact, the call of super class constructor is
       * necessary (!). Not adding a super class
       * constructor call in a child contractor is
       * completion error if the super class does not have
       * any default constructor (a constructor with no
       * parameters). If super class has a default
       * constructor and child does not call super contractor, default will be
       * called automatically. Need a proof? Create an
       * object of the class Demo implemented bellow.
       */

      /*
       * Just like the constructor call using this, the
       * super class constructor call must be the first
       * statement of a constructor. Which means, there is
       * no way to call both super constructor and this
       * constructor in the same constructor.
       */

      this.expandBy = expandBy;
      System.out.println("Constructor 4 (Super) called...");
   }

   public SuperStack(int[] array, int initialSize) {
      this(array, initialSize, 10);
      System.out.println("Constructor 5 (Super) called...");
   }

   public SuperStack(int[] array) {
      this(array, array.length);
      System.out.println("Constructor 6 (Super) called...");
   }

   public SuperStack(int size) {
      super(size);
      this.expandBy = 10;
      System.out.println("Constructor 7 (Super) called...");
   }

   public SuperStack() {
      this(10);
      System.out.println("Constructor 8 (Super) called...");
   }

   @Override
   public void push(int value) {
      if (top == array.length - 1) {
         array = Arrays.copyOf(array, array.length + expandBy);
                        // The array is resized and values are copied.
         System.out.println("Expanded, size = " + array.length);
      }

      /*
       * It is very usual that you need to call a super
       * class method which is overridden in the child
       * class. The parent method can be referred using
       * super.
       */
      super.push(value);
      /*
       * The use of super is necessary here. If not used,
       * the overridden method will be invoked
       */
   }

   public static void main(String[] args) {
      new Demo();
   }
}

class Demo extends SuperStack {
   int   top   = -35;

   /*
    * This possible but not usual that you'll name a
    * variable in a child class that is same with a
    * variable in the parent class. If you do so (I am
    * recommending NOT to) you can access the super class
    * variable with the keyword super.
    */

   public Demo() {
      System.out.println("Constructor 9 (Demo) called...");
      System.out.println("You see, the super class's default"
            + " constructor is called without specification.");
      System.out.println("This top = " + this.top + ", Super top = "
            + super.top);
      /*
       * The use of this for the child class's top is not
       * required. It is used to make it easy to
       * distinguish.
       */
   }
}


Last edited by BIT0102-Mohaimin on Sun Mar 20, 2011 3:13 pm; edited 1 time in total (Reason for editing : Title formatted)
BIT0102-Mohaimin
BIT0102-Mohaimin
Programmer
Programmer

Course(s) :
  • BIT

Blood Group : B+
Posts : 415
Points : 715

Back to top Go down

Java Re: Java Tutorial: Using Two Java Reference Keywords, this and super

Post by BIT0330-MOSHIUR Thu Oct 03, 2013 6:50 pm

The tutorials are very helpful. Please make some more.

BIT0330-MOSHIUR
Pre-Alpha Release
Pre-Alpha Release

Course(s) :
  • BIT

Blood Group : B+
Posts : 8
Points : 13

http://www.apprain.net/moshiur

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum