SlideShare une entreprise Scribd logo
1  sur  20
Compiled by:-Tanu Jaswal
Whenever a subclass needs to refer to its immediate
superclass, it can do so by use of the keyword super.
If your method overrides one of its superclass's methods, you
can invoke the overridden method through the use of the
keyword super.
You can also use super to refer to a hidden field (although
hiding fields is discouraged).
It has advantage so that you don’t to have to perform
operations in the “parentclass” again.
Only the immediate “parentclass’s” data and methods can be
accessed
Super has two general forms:-
The first calls the superclass' constructor.
The second is used to access a member of the
superclass that has been hidden by a member of
a subclass.
public class Superclass
{
  public void printMethod()
     {
        System.out.println("Printed in Superclass.");
     }
}
Here is a subclass,                        called        Subclass,           that
overrides printMethod():
 public class Subclass extends Superclass
    {
          public void printMethod() // overrides printMethod in Superclass
             {
                 super.printMethod();
                 System.out.println("Printed in Subclass");
             }
        public static void main(String[] args)
            {
                 Subclass s = new Subclass();
                 s.printMethod();
             }
      }
  Within         Subclass,       the    simple
name printMethod() refers to the one declared
in Subclass, which overrides the one
in Superclass.
 So, to refer toprintMethod() inherited
from Superclass, Subclass must use a qualified
name, using super as shown. Compiling and
executing Subclass prints the following:
              • Printed in Superclass.
               • Printed in Subclass.
 The syntax for calling a superclass constructor is
                           super();
                            --or–
                    super(parameter list);
With super(), the superclass no-argument constructor is
called.
With super(parameter list), the superclass constructor with
a matching parameter list is called.
If a constructor does not explicitly invoke a superclass
constructor, the Java compiler automatically inserts a call to
the no-argument constructor of the superclass.
If the super class does not have a no-argument
constructor,      you     will     get    a     compile-time
error. Object does have such a constructor, so ifObject is
the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its
superclass, either explicitly or implicitly, you might think
that there will be a whole chain of constructors called, all
the way back to the constructor of Object. In fact, this is
the case. It is called constructor chaining, and you need to
be aware of it when there is a long line of class descent.
class Box {
          private double width;
          private double height;
          private double depth;
Box(Box ob) {
// pass object to constructor
          width = ob.width;
          height = ob.height;
          depth = ob.depth;
          }
Box(double w, double h, double d) {
          width = w;
          height = h;
          depth = d;
          }
// constructor used when no dimensions specified
Box() {
          width = -1; // use -1 to indicate
          height = -1; // an uninitialized
          depth = -1; // box
          }
Box(double len) {
       width = height = depth = len;
       }
double volume() {
       return width * height * depth;
       }
    }
class BoxWeight extends Box {
       double weight;
BoxWeight(BoxWeight ob) {
       super(ob);
       weight = ob.weight;
       }
BoxWeight(double w, double h, double d, double m) {
       super(w, h, d);
       weight = m;
       }
BoxWeight() {
        super();
        weight = -1;
        }
BoxWeight(double len, double m) {
        super(len);
        weight = m;
        }
        }
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
}
}
The second form of super acts somewhat like
this, except that it always refers to the superclass of
the subclass in which it is used.
This usage has the following general form:
                    super.member
Here, member can be either a method or an
instance variable.
This second form of super is most applicable to
situations in which member names of a subclass hide
members by the same name in the superclass.
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
                i in superclass: 1
                 i in subclass: 2
Although the instance variable i in B hides the i
in A, super allows access to the I defined in the
superclass. As you will see, super can also be used
to call methods that are hidden by a subclass.
Sometimes a method will need to refer to the
object that invoked it. To allow this, Java
defines the this keyword.
this can be used inside any method to refer
to the current object. That is, this is always a
reference to the object on which the method
was invoked.
You can use this anywhere a reference to
an object of the current class’ type is
permitted.
THIS KEYWORD

The keyword this is useful when you need to
refer to instance of the class from its method.
The keyword helps us to avoid name conflicts.
As we can see in the program that we have
declare the name of instance variable and local
variables same.
Now to avoid the confliction between them we
use this keyword
class Rectangle{
  int length,breadth;
  void show(int length,int breadth){
  this.length=length;
  this.breadth=breadth;
  }
  int calculate(){
  return(length*breadth);
  }
}
public class UseOfThisOperator{
  public static void main(String[] args){
  Rectangle rectangle=new Rectangle();
  rectangle.show(5,6);
  int area = rectangle.calculate();
  System.out.println("The area of a Rectangle is : " + area);
  }
}
The area of a Rectangle is : 30.
Inthe example this.length and this.breadth refers
to the instance variable length and breadth while
length and breadth refers to the arguments passed in
the method.
THANK YOU

Contenu connexe

Tendances

Tendances (20)

Interface
InterfaceInterface
Interface
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance
InheritanceInheritance
Inheritance
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
virtual function
virtual functionvirtual function
virtual function
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 

En vedette (19)

Java keywords
Java keywordsJava keywords
Java keywords
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Abstract class
Abstract classAbstract class
Abstract class
 
Selenium ide material (2)
Selenium ide material (2)Selenium ide material (2)
Selenium ide material (2)
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Fundamentals
FundamentalsFundamentals
Fundamentals
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Java String
Java String Java String
Java String
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Keyboard
KeyboardKeyboard
Keyboard
 
Black hole ppt
Black hole pptBlack hole ppt
Black hole ppt
 
Leonardo Da Vinci Ppt
Leonardo Da Vinci PptLeonardo Da Vinci Ppt
Leonardo Da Vinci Ppt
 
zigbee full ppt
zigbee full pptzigbee full ppt
zigbee full ppt
 
Time travel
Time travelTime travel
Time travel
 
Virtual keyboard ppt
Virtual keyboard pptVirtual keyboard ppt
Virtual keyboard ppt
 

Similaire à Ppt on this and super keyword

Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritanceraksharao
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .happycocoman
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Keyword of java
Keyword of javaKeyword of java
Keyword of javaJani Harsh
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear ASHNA nadhm
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in javaAtul Sehdev
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 

Similaire à Ppt on this and super keyword (20)

Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Java unit2
Java unit2Java unit2
Java unit2
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Java misc1
Java misc1Java misc1
Java misc1
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Sdtl assignment 03
Sdtl assignment 03Sdtl assignment 03
Sdtl assignment 03
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Core java oop
Core java oopCore java oop
Core java oop
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Chap11
Chap11Chap11
Chap11
 

Dernier

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Dernier (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Ppt on this and super keyword

  • 2. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). It has advantage so that you don’t to have to perform operations in the “parentclass” again. Only the immediate “parentclass’s” data and methods can be accessed
  • 3. Super has two general forms:- The first calls the superclass' constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass.
  • 4. public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } }
  • 5. Here is a subclass, called Subclass, that overrides printMethod(): public class Subclass extends Superclass { public void printMethod() // overrides printMethod in Superclass { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } }
  • 6.  Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass.  So, to refer toprintMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following: • Printed in Superclass. • Printed in Subclass.
  • 7.  The syntax for calling a superclass constructor is super(); --or– super(parameter list); With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called. If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
  • 8. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so ifObject is the only superclass, there is no problem. If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.
  • 9. class Box { private double width; private double height; private double depth; Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box }
  • 10. Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } class BoxWeight extends Box { double weight; BoxWeight(BoxWeight ob) { super(ob); weight = ob.weight; } BoxWeight(double w, double h, double d, double m) { super(w, h, d); weight = m; }
  • 11. BoxWeight() { super(); weight = -1; } BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); } }
  • 12. The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.
  • 13. class A { int i; } class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B }
  • 14. void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }
  • 15. This program displays the following: i in superclass: 1 i in subclass: 2 Although the instance variable i in B hides the i in A, super allows access to the I defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass.
  • 16. Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted.
  • 17. THIS KEYWORD The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword
  • 18. class Rectangle{ int length,breadth; void show(int length,int breadth){ this.length=length; this.breadth=breadth; } int calculate(){ return(length*breadth); } } public class UseOfThisOperator{ public static void main(String[] args){ Rectangle rectangle=new Rectangle(); rectangle.show(5,6); int area = rectangle.calculate(); System.out.println("The area of a Rectangle is : " + area); } }
  • 19. The area of a Rectangle is : 30. Inthe example this.length and this.breadth refers to the instance variable length and breadth while length and breadth refers to the arguments passed in the method.