SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados (20)

06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Interface
InterfaceInterface
Interface
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Method overriding
Method overridingMethod overriding
Method overriding
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 

Destaque (20)

Java keywords
Java keywordsJava keywords
Java keywords
 
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)
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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.