I was going through AWT for the first time in java, I found how to create a button in it by creating an object for the button - for instance b1 - and to add this component to the container by using add method [add(b1)] . In this case what I noticed was, add() is a method of some parent class may be container which has been inherited, and the button b1 was directly added to it without having the reference calling the method add() ( .add() ) and that is petty confusing for me. How would a method be called without using the dot operator?
Asked
Active
Viewed 98 times
2
-
2Please give us a code example. We have no way of knowing what you are talking about without at least a bit of code. – ameed Jul 23 '13 at 20:05
-
1@Keppil has your answer (1+ to his answer), but also I want to suggest that you not learn to code with AWT as this is quite old and way out of date. Swing is better, although it too is somewhat out of date. – Hovercraft Full Of Eels Jul 23 '13 at 20:09
-
Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Jul 24 '13 at 03:23
2 Answers
4
If the method belongs to the object you are currently in, either directly or through inheritance from a parent, you don't have to prefix the method with anything. You can just use
add();
If you want to be extra clear, you can use the this
keyword to specify that the method belongs to the object you are in. This will work exactly the same as the above:
this.add();

Keppil
- 45,603
- 8
- 97
- 119
-
Also, if you're in an anonymous class - you can call `MyClassName.this` to get the reference for the parent. – sdasdadas Jul 23 '13 at 22:23
3
this.add()
and
add()
are almost always the same - they compile to the same byte-code. Although, see this similar question: In Java, what is the difference between this.method() and method()? for more details in depth, particularly regarding static methods, and also calling methods on/in inner classes.