'Super' Keyword & Casting සිංහලෙන්

 


'Super' Keyword


Sub class එකක සිට Super class එකක ඇති දේවල් call කිරීමට super යන keyword එක භාවිතා කරයි. මෙය පහත උදාහරණයෙන් පැහැදිලි කර ගනිමු.

        
        class Monkey {
                Monkey ( ) { }
                void Climb ( ) { }
                int hands = 2;
        }
        class Men extends Monkey {
                Man ( ) {
                    Super ( );
                    Super . Climb ( );
                    Super . hands = 1;
                    }
                    void Climb ( ) { }
        }

මෙහි super class එක වන්නෙ Monkey වේ. sub class එක වන්නෙ Men වේ. class Men එක තුල Super ( ) ලෙස keyword එක යෙදීම මඟින් class Monkey තුල ඇති දේවල් call කිරීමට හැකියි. මේ සඳහා තවත් උදාහරණ පහත දැකිවේ.




ඉහත ඇති java code එකෙහි class Test එක තුල ඇති main method එක තුල sub class එක භාවිතා කර  object එකක් සදා ඇත. ඉන් පසු එය භාවිතා කර sub class එක තුල ඇති printColor ( ) { } නමින් ඇති method එක call කර ඇත. එම නිසා පලමුව එහි ඇති System . out . println (color); මඟින් එම class එක තුලම ඇති color variable එක call වී Pink යනුවෙන් print වේ. දෙවනුව ඇති System . out . println (super . color); මඟින් super class එක තුල ඇති color variable එක call වී Red යනුවෙන් print වේ. System . out . println (super . color); හී super යනුවෙන් යොදා ඇති නිසා කිසිදු ගැටලුවකින් තොරව sub class එකේ සිටම super class එක access කල හැකියි. මේ පිලිඹඳ තව උදාහරණ පහත දැක් වේ.

                            01.



                            02. 


                            
                            03.




Casting

Castin යනු යම් කිසි class එකක ඇති දේවල් වෙනත් දෙයකට පැවරීමයි. මෙහි කොටස් දෙකක් පවතී.
           
            01.  Upcasting
            02.  Downcasting

01. Upcasting

Super class එකෙහි ඇති variables ( Reference ) එකකට sub class එකෙහි ඇති Object එකක් assign කිරීම Upcasting වේ.

02. Downcasting

Super class variable ( Reference ) එකකට දමන ලද sub class Object එක නැවත sub class variable එකක් කිරීම Downcasting වේ.



                by Janitha Pramudika Kandegedara


glowing buttons
youtube
LinkedIn
instagram

Comments

Popular posts from this blog

Method Overloading සිංහලෙන්

Main method | Constructor සිංහලෙන්