SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
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)

Java program structure
Java program structureJava program structure
Java program structure
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java IO
Java IOJava IO
Java IO
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Abstract class
Abstract classAbstract class
Abstract class
 

Destaque (18)

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

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

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 

Último (20)

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 

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.