public class foo{
    public int var = 5;
    public void method(int var){
        System.out.println(var);
    }
foo myfoo = new foo();
myfoo.method(1);


The variable var has been defined twice. Once as a object scope varbiable and once as a parameter (which is localy scoped). What will method print 1 or 5? There is a clearly ambiguity here so which one should Java go for?

Java will always go for the local variable first. This behaviour is known as shadowing variables. It can be useful when making code more readable but can cause issues.

To access the object variable you need to specify the keyword this first

System.out.println(this.var);

This will print out the object variable rather than the local variable.

Classes can also have the same name as long as they are in seperate packages. For example -

Both of these classes are called Date. One represents a Date on the desktop while the other represents a Date from a database. If you had to use both you must specify the fully qualified name of the class. This essentially means you must write down the package and class name when you try and reference it.

java.util.Date deskDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date();

next summary >>

 
Basics
Menu
Search