Loading...
Logo
Processing Forum
In the constructor I say this.file (referring to global file variable declared above) equals file (referring to the file variable name in the constructor). Then when I say addFolder(file) I get the error "The method addFolder(MainTab.Node) in the type MainTab is not applicable for the arguments (File)".

This makes sense because I am sending addFolder a file instead of a Node but when I was trying to figure out how to fix it I found out that it works with addFolder(this) but I don't understand why??? "this" should equal the same thing as file no?

Copy code
  1. class Node {
  2.   int childCount;
  3.   Node[] children;
  4.   File file;
  5.  
  6.   Node(File file) {
  7.     this.file = file;
  8.    
  9.     if(file.isDirectory()) {
  10.       addFolder(file);
  11.     }
Main Tab

Copy code
  1. void addFolder(Node folder) {
  2.   if(folderCount == folders.length) {
  3.     folders = (Node[]) expand(folders);
  4.   }
  5.   folders[folderCount++] = folder;
  6. }
Thank you!
McK

Replies(3)

"this" points to the current object:

Copy code
  1. void setup(){
  2.   Test test = new Test(12);
  3.   println("current instance: "+ test);
  4. }
  5. class Test{
  6.   int var = 0;
  7.   Test(int var){
  8.     this.var = var;
  9.     println("in constructor:   "+ this);
  10.   }
  11. }

you can see, that both times, the same address is printed.
so, outside of the class you can access members and methods by "test.var", and inside a class, you can access the member/methods by "this.var" (or just "var").


http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Makes perfect sense, because the this in the Node class will be an object of the type Node, which is exactly what the addFolder() function is expecting. See the difference when you put the same code into a NotANode class. Then it won't work, because in that case, this will be a NotANode object.

Because this refers to the object itself. this.something refers to stuff in that object, like this.file etc.

Hope that makes sense...

Code Example
Copy code
  1. class Node {
  2.   File file;
  3.   Node(File file) {
  4.     this.file = file;
  5.     if (file.isDirectory()) {
  6.       addFolder(this);
  7.     }
  8.   }
  9. }

  10. class NotANode {
  11.   File file;
  12.   NotANode(File file) {
  13.     this.file = file;
  14.     if (file.isDirectory()) {
  15.       addFolder(this);
  16.     }
  17.   }
  18. }

  19. void addFolder(Node folder) {
  20.   // do stuff
  21. }
Okay. That does make sense. Perfect sense.

Thank you!