Post on 08-Apr-2018
8/6/2019 Venkat Doubt
1/3
keyword : this
'this' is used for pointing the current class instance. It can be used with variables or methods. Look into the following example:
class Test{
private int i=10;public void m(){
System.out.println(this.i);}
}In the above code this is used for the current instance. Since this is instanceof a class it cannot be used inside a static method.keyword : super
'super' is used for pointing the super class instance. See the following example.
class A{
int k = 10;}class Test extends A{
public void m(){
System.out.println(super.k);}
}In the above example the super keyword is used for accessing the super class var
iable.
Example 2:
package InnerclassDemo;
public class venkatDoubt {
String s = "siva";void method1(){
System.out.println(" this my first method");
} class innerClassEx {String s="tea";void method2(){
System.out.println(" this my second method");
}void hh() {
String s="oooo";System.out.println("hi :" + s +"...."+this.s +"..."+venk
atDoubt.this.s);}
class innerInnerClass2{void jj(){
8/6/2019 Venkat Doubt
2/3
}}
}public static void main(String args[]){
venkatDoubt.innerClassEx inner =new venkatDoubt().new innerClassEx();inner.hh();inner.method2();
}
}
output:hi :oooo....tea...sivathis my second method
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Anonymous Inner Classes in Java
If an inner class has been declared without a name and within a code block (typically within the body of a method) then such an inner class is called an anonymous inner class. Since such an inner class doesn't have a name associated, so it'll be accessible only at the point where it is defined.
Example:
class Popcorn {public void pop() {
System.out.println("popcorn");}
}
class Food {public static void main(String args[]){Popcorn p = new Popcorn() {
public void pop2() {System.out.println("anonymous popcorn");
}};p.pop();}
}
output:
popcorn
---------------------------------------------------------------------------------------
8/6/2019 Venkat Doubt
3/3
A static java inner class cannot have instances.A non-static java inner class can have instances that belong to the outer class.
package InnerclassDemo;
class StaticmethodInnerClass {
class Employee{
int grossSalary(int basicSalary){
return basicSalary+2000;}
}
static class Worker{
int wages(int workDays)
{return workDays*200;
}}
public static void main(String args[])
{
// Create object to inner class
StaticmethodInnerClass.Employee innerEmp=new StaticmethodInnerClass().new Employee();
System.out.println("Employee GrossSalary :"+innerEmp.grossSalary(15000));
// Create object to static inner class
StaticmethodInnerClass.Worker innerWorker=new StaticmethodInnerClass.Worker();
System.out.println("Worker wages :"+innerWorker.wages(20));
}}
output:Employee GrossSalary :17000Worker wages :4000