Well i know the basic difference which is in C++ this is a pointer whilst Java is a reference to a class... I have a confusion though since am new in Java, can you reference a super class with "this"? more so, is the an underlying difference between the C++ vs Java "this"

Recommended Answers

All 7 Replies

Well i know the basic difference which is in C++ this is a pointer whilst Java is a reference to a class... I have a confusion though since am new in Java, can you reference a super class with "this"? more so, is the an underlying difference between the C++ vs Java "this"

You use the "super" keyword to reference the adjacent base class in Java--

class MyPackageAccessClass extends AccessClass{

         public MyPackageAccessClass(String name){
                   super(name); // call to super constructor
                   super.validateInformation(name); // call to method validateInformation in adjacent base class
         }

}

--and when I say adjacent I mean the following base class for the calling derived class.

For example, if ScholarlyStudent extends from Student and Student extends from Person, the adjacent base class (super) of ScholarlyStudent is Student and not Person.

I'm a bit fuzzy on the ultimate meaning of "this" in C++ to make a valid comparison between what "this" is pointing to in C++ against the meaning of "this" in Java. Will edit soon--

Edit:

The this pointer (C++ only)

The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.

A static member function does not have a this pointer

I suppose the "this" modifier in C++ is necessary when accessing a super data type when declaring/defining a derived type of the super type when you need to tell the compiler you want to use a data type that exists within the super type, within the scope of the derived type. This seems valid because, as the quote implies the this modifier holds the reference to the class and should therefore have all of the information of the class, including inherited methods.

Here's a test I ran--

#include <iostream>
#include <cstdlib>

using namespace std;

struct Person{

    public:
            void run(){
                cout << "Person Running..." << endl;
            }

};

struct Student : public Person{

    public:
            Student(){
                Person::run(); // calling the base class run
                this->run(); // invoking non-virtual run to see if this-> has same behavior as Person:: - seems not
                run(); // same behavior as this->
            }

            void run(){
                cout << "Student Running" << endl;
            }

};

int main()
{
    Student s;
    cin.get();
    return 0;
}

I suppose the "this" modifier in C++ is necessary when accessing a super data type when declaring/defining a derived type of the super type when you need to tell the compiler you want to use a data type that exists within the super type, within the scope of the derived type.

Emh.. NO! Aren't you contradicting yourself here... Your code "this->run()" does not access a Person (super structure) run, but the run in student (current structure) ...

Have a look at this Java class

public class ConfirmExitDialog extends JFrame {

    public ConfirmExitDialog() {

        // -------------------------------------------------------------
        // Call super class constructor plus set the size for the Window
        // -------------------------------------------------------------
        super("Confirm Exit Dialog Example");
        this.setSize(350, 150);

        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        // -----------------
        // Simple text label
        // -----------------
        JLabel label1 = new JLabel("Confirm Exit Dialog Example", JLabel.LEFT);

        // -----------------------------------------------------
        // Add all buttons directory to the frame's content pane
        // -----------------------------------------------------
        contentPane.add(label1, BorderLayout.SOUTH);
        
    }

    protected void processWindowEvent(WindowEvent e) {

        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
        
            int exit = JOptionPane.showConfirmDialog(this, "Are you sure?");
            if (exit == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
            
        } else {

            super.processWindowEvent(e);
        }
    }

    public static void main(String[] args) {
        ConfirmExitDialog mainFrame = new ConfirmExitDialog();
        mainFrame.setVisible(true);
    }
    
}

Note that setSize() is not a member of ConfirmExitDialog() but inherited from a super class... now "this" is used to access it??? That's where my confusion is!! isn't this a reference to ConfirmExitDialog class?

I'm sorry, my quote wasn't complete.

I meant only when the derived object itself didn't have the definition of the method within its class but in the base class and you needed to specify where you were calling the method (had problems before with calling methods in a base class using Dev-Cpp and a non-standard compiler).

Since setSize(int, int) is inherited from the derived class, it is technically a part of the class (in Java) and therefore you can call upon this.setSize(int, int).

However, if you needed to differentiate between methods within the derived type and the super type you'd use this or super respectively.

Here's the modified example from my previous post that exercises this same behavior in C++

#include <iostream>
#include <cstdlib>

using namespace std;

void run(){
    cout << "namespace running" << endl;
}

struct Person{

    public:
            virtual void run(){
                cout << "Person Running..." << endl;
            }

};

struct Student : public Person{

    public:
            Student(){
                Person::run(); // calling the base class run
                this->run(); // invoking non-virtual run to see if this-> has same behavior as Person:: - since run isn't re-defined in this class it should
                run(); // same behavior as this->
            }

       // commenting out the run defined in this class
        //    void run(){
         //       cout << "Student Running" << endl;
          //  }

};

int main()
{
    Student s;
    cin.get();
    return 0;
}

Since setSize(int, int) is inherited from the derived class, it is technically a part of the class (in Java) and therefore you can call upon this.setSize(int, int).

Really!! Then what's the point of using "this", why not just setSize(), like you would do in C++?

One last thing to note--

The major use of this in Java is to unmask globally scoped variable from local variables/parameters in methods, however one thing you should know is that this is also used for calling constructors within the SAME class that the this modifier is used--

public class Person{

     public Person(){
          this("String"); // call to the constructor (that takes a string) in this class
     }
 
     public Person(String s){
     }

}

--but this has to be used within the first line of code.

Inversely, if you use super(<parameters>) instead of this(<parameters>) you will be calling the constructor of the base class and not a constructor within the calling class. Also, the super constructor call must be the first line of code within a constructor.

public class Student{

     public Student(String name){
     }

}
public class Person extends Student{

       public Person(){
          super("No name"); 
       }

}

--I'm sure that example wasn't needed. It was simply to show the differences stated.

Really!! Then what's the point of using "this", why not just setSize(), like you would do in C++?

You could, and in fact I'd encourage that more than using "this" - it makes code less cluttered and complicated. Only use this when unmasking globally scoped variables or when calling a constructor declared within the calling class - just be careful of cyclic constructor calls with "this."

> Note that setSize() is not a member of ConfirmExitDialog() but inherited from a super
> class... now "this" is used to access it??? this simply stands for the reference to current instance in consideration. The execution of setSize() is no different than this.setSize() for the very same reason. They both end up calling the Parent class's method setSize() or throwing a compile time error in case no such method exists. This look up is not restricted to the parent class but continues down the inheritance hierarchy. To sum it up, this , when used in instance method and constructor refers to the current instance executing that very method / constructor.

> Note that setSize() is not a member of ConfirmExitDialog() but inherited from a super
> class... now "this" is used to access it??? this simply stands for the reference to current instance in consideration. The execution of setSize() is no different than this.setSize() for the very same reason. They both end up calling the Parent class's method setSize() or throwing a compile time error in case no such method exists. This look up is not restricted to the parent class but continues down the inheritance hierarchy. To sum it up, this , when used in instance method and constructor refers to the current instance executing that very method / constructor.

A much better explanation, thank you.

Edit: I'm surprised nobody marked me for goofing and making Person extend Student @_@

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.