SlideShare una empresa de 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

Más contenido relacionado

La actualidad más candente

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in javaanshu_atri
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Multiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxMultiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxRkGupta83
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 

La actualidad más candente (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
OOP java
OOP javaOOP java
OOP java
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Multiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxMultiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptx
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Exception handling
Exception handlingException handling
Exception handling
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 

Destacado (18)

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)
 
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
 

Similar 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
 

Similar 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

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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 

Último (20)

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...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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 the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

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.