Our social:

Thursday, 17 December 2015

Can we typecast implicit variable "this" and "super" if yes then how, if no then why?

:Yes we can typecast implicit variable "this". this variable is a special referenced type variable that is used to denote current object class reference. It will internally stores the value of current object class reference.
code snapshop:


Now our question is if yes the how it is possible.....
Simple, we have a class called  A that bydefault extending Object class so it is good to take this example..Now i have created an object of class A and i want to store class A type variable value in Object type reference variable.
A a=new A();
Object obj1=(Object)this;
here this variable contains A class information  and that is going to be store in obj1 that is of Object type.
so in this case we are able to typecast implicit variable "this"
full code is looks something like this:

------------------------------------------------------------------------------------------------------------------------
class Atest 
{
void m1(){
Object obj1=(Object)this;//here obj1 is Object type super class ref variable 
                        //and we are passing this variable value(subclass type) to super class
System.out.println(obj1.getClass());
}
public static void main(String[] args) 
{
Atest a1=new Atest();
a1.m1();
}
}

According to my analyzation "super" variable type casting is not possible.....
why, i will post in next post..........

                                                                                                             Thank you(Smartyy Sunny)

3 comments:

  1. Typecasting is 'OK', but very bad example, It is in general used for more derived class, not a class that it already implements.

    ReplyDelete
    Replies
    1. Object class of java is super class of every java class. Now here m storing A class type reference in object class that is subclss of Object. Yes ur ri8 Mr. Parimal Raj , this example is very simple..but i have typed this program only for proof of concept..well thankyou to giving intimation to me. I will post a good example on it. thank you....

      Delete
  2. class Super
    {

    }
    class Derived extends Super
    {
    void typeCastLogic(){
    Super super1=(Super)this; //we are assinging Test type in A Type
    System.out.println(super1.getClass());
    }
    public static void main(String[] args){
    Derived dd=new Derived();
    dd.typeCastLogic();

    }
    }

    ReplyDelete