Sunday, January 1, 2012

Usage of 'this' keyword in preventing instance variable hiding in Java

Example



import java.io.*;
class SuperClass
{
int a;
SuperClass()
{}
v
oid Display1()

{
if (a%2==0)
{
System.out.println("first value is divisible by 2");
}
else
{
System.out.println("first value is not divisible by 2");
}
}
}
class SubClass extends SuperClass
{
int c;
SubClass(int d,int e)
{
this.a=d;
c=e;
}
void Display()
{
if (this.a%c==0)
{
System.out.println(this.a+": is divisible by :"+c);
}
else
{
System.out.println(this.a+":is not divisible by:"+c);
}
}
}
public class A404305
{
public static void main(String args[])
throws IOException
{
int f,g;
BufferedReader br;
br=new BufferedReader(new InputStreamReader(System.in));
f=Integer.parseInt(br.readLine());
g=Integer.parseInt(br.readLine());
SubClass s=new SubClass(f,g);
s.Display();
SuperClass s1=new SuperClass();
s1.Display1();


}
}

No comments:

Post a Comment