SlideShare une entreprise Scribd logo
1  sur  23
Collaborate


Knowledge Byte
    In this section, you will learn about:


         •   The super and this keywords
         •   The nested try and catch block




 ©NIIT                          Collaborate   Lesson 1C / Slide 1 of 23
Collaborate


The super and this Keywords
    •    The super keyword
           • Java provides the super keyword that enables a subclass to refer to its
             superclass. The super keyword is used to access:
                • superclass constructors
                • superclass methods and variables
           • The syntax to invoke the constructor of a superclass using the super()
             method is:
             super (<parameter1>, <parameter 2>,..,<parameterN>);
             In the above syntax, <parameter1>, <parameter 2>,..,<parameterN>
             refer to the list of parameters that you need to pass to the constructor of
             the superclass.




 ©NIIT                           Collaborate                   Lesson 1C / Slide 2 of 23
Collaborate


The super and this Keywords (Contd.)
    •    The super Keyword (Contd.)
           • If no parameters are passed to the super() method, it invokes the default
             constructor of the superclass.
           • If the superclass contains the overloaded constructor, you can pass
             parameters to the super() method to invoke a particular constructor.
           • When you use the super() method in the constructor of the subclass, it
             should be the first executable statement in the constructor.




 ©NIIT                          Collaborate                   Lesson 1C / Slide 3 of 23
Collaborate


The super and this Keywords (Contd.)
    •    The super Keyword (Contd.)
           • The syntax to access the member variable of a superclass is:
             super.<variable>;
           • The subclass can also access the member methods of the superclass using
             the super keyword.




 ©NIIT                         Collaborate                  Lesson 1C / Slide 4 of 23
Collaborate


The super and this Keywords (Contd.)
    •    The this Keyword
         • The this keyword is used to refer to the current object.
         • You can use the this keyword when a method defined in a Java class
              needs to refer to the object used to invoke that method.
         • The following code snippet shows how to use the this keyword:
              Book(int bcode, double bprice)
              {
              this.bookCode=bcode;
              this.bookPrice=bprice;
              }
              In the above code snippet, the this keyword refers to the object that
              invokes the Book() constructor.




 ©NIIT                        Collaborate                   Lesson 1C / Slide 5 of 23
Collaborate


The super and this Keywords (Contd.)
    •    The this Keyword (Contd.)
         • Another situation where you can use the this keyword is when the local
              and instance variables have the same name.
         • The following code snippet shows how to use the this keyword when
              instance and formal parameters have the same name:
              Book(int bcode, double bprice)
              {
              this.bcode=bcode;
              this.bprice=bprice;
              }
              In the above code snippet, this keyword refers to the instance variables,
              bcode and bprice. The values of the formal parameters, bcode and
              bprice of the Book() constructor are assigned to the instance variables.




 ©NIIT                        Collaborate                    Lesson 1C / Slide 6 of 23
Collaborate


The super and this Keywords (Contd.)
    •    The this Keyword (Contd.)
          • In addition, you can use the this keyword in a constructor of a class to
               invoke another constructor of the class.
          • Unlike the super keyword, the this keyword can invoke the
               constructor of the same class.
          • The following code snippet shows how to invoke a constructor using
               the this keyword:
               class Book {
               public Book(String bname)        {
                   this(bname, 1001); }
               public Book(String bname, int bcode) {
                   bookName=bname;
                   bookCode=bcode; }
                }


 ©NIIT                       Collaborate                   Lesson 1C / Slide 7 of 23
Collaborate


The Nested try-catch Block
    •    The try-catch block is used to handle exceptions in Java applications.
    •    You can enclose a try-catch block in an existing try-catch block.
    •    The enclosed try-catch block is called the inner try-catch block, and the
         enclosing block is called the outer try-catch block.
    •    If the inner try block does not contain the catch statement to handle an
         exception then the catch statement in the outer block is checked for the
         exception handler.
    •    The following syntax shows how to create a nested try-catch block:
         class SuperClass
         {
         public static void main(String a[])
         {
         <code>;
         try
         {

 ©NIIT                        Collaborate                   Lesson 1C / Slide 8 of 23
Collaborate


The Nested try-catch Block (Contd.)
    •    The following syntax shows how to create a nested try-catch block: (Contd.)
              <code>;
              try
              {
              <code>;
              }
              catch(<exception_name> <var>)
              {
              <code>;
              }
         }
              catch(<exception_name> <var>)
              {
              <code>;
              } } }
 ©NIIT                        Collaborate                  Lesson 1C / Slide 9 of 23
Collaborate


From the Expert’s Desk

    In this section, you will learn:


         •    Best practices on:
              • The Use of final Keyword
         •    Tips on:
              • The Use of Constructors
              • The finally Block
         •    FAQs




 ©NIIT                           Collaborate   Lesson 1C / Slide 10 of 23
Collaborate


Best Practices
The Use of final Keyword
    •    The final keyword can be used with:
         • A variable
         • A method
         • A class
    •    The use of the final keyword prevents you from changing the value of a
         variable.
    •    When you use the final keyword with a variable, the variable acts as a
         constant.
    •    It is recommended that you name the final variable in uppercase.




 ©NIIT                        Collaborate                 Lesson 1C / Slide 11 of 23
Collaborate


Best Practices
The Use of final Keyword (Contd.)
    •    The syntax to declare the final variable is:
         final int MY_VAR=10;
         In the above syntax, the MY_VAR variable is declared as final. As a result,
         the value of the variable cannot be modified.
    •    The final keyword is used with methods and classes to prevent method and
         class overriding while implementing inheritance in a Java application.
    •    If a method in a subclass has the same name as the final method in a
         superclass, a compile time error is generated.




 ©NIIT                        Collaborate                  Lesson 1C / Slide 12 of 23
Collaborate


Best Practices
The Use of final Keyword (Contd.)
    •    The following syntax shows how to declare the final method:
         class SuperClass
         {
         final void finalMethod()
         {}
         }
    •    Similarly, if a class is declared final, you cannot extend that class.
    •    If you extend the final class, a compile time error is generated.




 ©NIIT                          Collaborate                    Lesson 1C / Slide 13 of 23
Collaborate


Best Practices
The Use of final Keyword (Contd.)
    •    The following syntax shows how to declare the final class:
         final class SuperClass
         {
         //This is a final class.
         }
         In the preceding syntax, the SuperClass class is declared as final.




 ©NIIT                         Collaborate                  Lesson 1C / Slide 14 of 23
Collaborate


Tips
The Use of Constructors
    •    Consider a Java application that contains multiple classes. Each class is
         extended from another class in the application and contains a default
         constructor.
    •    When the application is executed, the constructors are called in the order in
         which the classes are defined.
    •    For example, there are three classes in a Java application: Class1, Class2,
         and Class3. Class2 extends Class1, and Class3 extends Class2. When you
         create an instance of Class 3, the constructors are called in the following
         order:
         • Class1 constructor
         • Class2 constructor
         • Class3 constructor


 ©NIIT                         Collaborate                  Lesson 1C / Slide 15 of 23
Collaborate


Tips
The finally Block
    •    The finally block associated with a try block is executed after the try or catch
         block is completed.
    •    It is optional to associate the finally block with a try block, but if the try block
         does not have a corresponding catch block, you should provide the finally
         block.




 ©NIIT                          Collaborate                     Lesson 1C / Slide 16 of 23
Collaborate


FAQs
    •    Can classes inherit from more than one class in Java?

         No, a class cannot be inherited from more than one class in Java. A class is
         inherited from a single class only. However, multi-level inheritance is
         possible in Java. For example, if class B extends class A and class C extends
         class B, class C automatically inherits the properties of class A.


    •    What is the difference between an interface and a class?

         Both, class and interface, contain constants and methods. A class not only
         defines methods but also provides their implementation. However, an
         interface only defines the methods, which are implemented by the class that
         implements the interface.




 ©NIIT                         Collaborate                  Lesson 1C / Slide 17 of 23
Collaborate


FAQs (Contd.)
    •    Do you have to catch all types of exceptions that might be thrown by Java?

         Yes, you can catch all types of exceptions that are thrown in a Java
         application using the Exception class.


    •    How many exceptions can you associate with a single try block?

         There is no limit regarding the number of exceptions that can be associated
         with a single try block. All the exceptions associated with a try block should
         be handled using multiple catch blocks.




 ©NIIT                         Collaborate                   Lesson 1C / Slide 18 of 23
Collaborate


FAQs (Contd.)
    •    What are the disadvantages of inner classes?

         The inner classes have various disadvantages. The use of inner class
         increases the total number of classes in your code. The Java developers also
         find it difficult to understand to implement the concept of inner class within
         the programs.


    •    What is the level of nesting for classes in Java?

         There is no limit of nesting classes in Java.




 ©NIIT                          Collaborate                  Lesson 1C / Slide 19 of 23
Collaborate


Challenge
    1.   You can access particular constructors in the superclass using
         ______operator.
    2.   Which of the following exceptions is raised when a number is divided by
         zero:
         a.    NullPointerException
         b.    ArithmeticException
         c.    ArrayIndexOutOfBoundsException
         d.    NumberFormatException
    3.   You can have more than one finally block for an exception-handler.
         (True/False)
    4.   Match the following:
          a. public 1. Ensures the value is not changed in the classes that
                        implement an interface.
         b. static 2. Ensures that are able to override the data members in
                        unrelated classes.
         c. final    3. Ensures that you cannot create an object of the interface.
 ©NIIT                         Collaborate                  Lesson 1C / Slide 20 of 23
Collaborate


Challenge (Contd.)
  1.     The following code is a jumbled code. Rearrange the following code to make it
         executable:
         public class Excp
         {
              public static void main(String args []) {
              int num1, num2, num3;
              num1 = 10;
              num2 = 0;
              catch(ArithmeticException e)
              {
                   System.out.println(" Error Message");
              } try
                   {
                              num3 = num1/num2;
                   }
 ©NIIT                          Collaborate                 Lesson 1C / Slide 21 of 23
Collaborate


Solutions to Challenge

    •       dot
    •       b. ArithmeticException
    •       False
    •       a. 2
            b. 1
            c. 3
    5.      public class Excp
                            {
                      public static void main(String args [])
                      {
                      int num1, num2, num3;
                      num1 = 10;
                      num2 = 0;

 ©NIIT                      Collaborate                Lesson 1C / Slide 22 of 23
Collaborate


Solutions to Challenge (Contd.)
         try
         {
                 num3 = num1/num2;
         }
         catch( ArithmeticException e)
         {
                  System.out.println(" Error Message");
         }




 ©NIIT                     Collaborate              Lesson 1C / Slide 23 of 23

Contenu connexe

Tendances

Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)smumbahelp
 
Questions of java
Questions of javaQuestions of java
Questions of javaWaseem Wasi
 
A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation Ayush Gupta
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
OOPs difference faqs-3
OOPs difference faqs-3OOPs difference faqs-3
OOPs difference faqs-3Umar Ali
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in javasureshraj43
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiersKhaled Adnan
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Session 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access ModifiersSession 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access ModifiersPawanMM
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 

Tendances (20)

Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
Questions of java
Questions of javaQuestions of java
Questions of java
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
OOPs difference faqs-3
OOPs difference faqs-3OOPs difference faqs-3
OOPs difference faqs-3
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Inheritance
InheritanceInheritance
Inheritance
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Java session13
Java session13Java session13
Java session13
 
Session 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access ModifiersSession 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access Modifiers
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similaire à The super and this Keywords

Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingWondimuBantihun1
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#Muhammad Younis
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1javatrainingonline
 
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...Simplilearn
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdf04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdfmarkbrianBautista
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.ManojSatishKumar
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 

Similaire à The super and this Keywords (20)

Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 2-1 a
Dacj 2-1 aDacj 2-1 a
Dacj 2-1 a
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programming
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
 
31 days Refactoring
31 days Refactoring31 days Refactoring
31 days Refactoring
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdf04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdf
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 

Plus de Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 

Dernier

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Dernier (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

The super and this Keywords

  • 1. Collaborate Knowledge Byte In this section, you will learn about: • The super and this keywords • The nested try and catch block ©NIIT Collaborate Lesson 1C / Slide 1 of 23
  • 2. Collaborate The super and this Keywords • The super keyword • Java provides the super keyword that enables a subclass to refer to its superclass. The super keyword is used to access: • superclass constructors • superclass methods and variables • The syntax to invoke the constructor of a superclass using the super() method is: super (<parameter1>, <parameter 2>,..,<parameterN>); In the above syntax, <parameter1>, <parameter 2>,..,<parameterN> refer to the list of parameters that you need to pass to the constructor of the superclass. ©NIIT Collaborate Lesson 1C / Slide 2 of 23
  • 3. Collaborate The super and this Keywords (Contd.) • The super Keyword (Contd.) • If no parameters are passed to the super() method, it invokes the default constructor of the superclass. • If the superclass contains the overloaded constructor, you can pass parameters to the super() method to invoke a particular constructor. • When you use the super() method in the constructor of the subclass, it should be the first executable statement in the constructor. ©NIIT Collaborate Lesson 1C / Slide 3 of 23
  • 4. Collaborate The super and this Keywords (Contd.) • The super Keyword (Contd.) • The syntax to access the member variable of a superclass is: super.<variable>; • The subclass can also access the member methods of the superclass using the super keyword. ©NIIT Collaborate Lesson 1C / Slide 4 of 23
  • 5. Collaborate The super and this Keywords (Contd.) • The this Keyword • The this keyword is used to refer to the current object. • You can use the this keyword when a method defined in a Java class needs to refer to the object used to invoke that method. • The following code snippet shows how to use the this keyword: Book(int bcode, double bprice) { this.bookCode=bcode; this.bookPrice=bprice; } In the above code snippet, the this keyword refers to the object that invokes the Book() constructor. ©NIIT Collaborate Lesson 1C / Slide 5 of 23
  • 6. Collaborate The super and this Keywords (Contd.) • The this Keyword (Contd.) • Another situation where you can use the this keyword is when the local and instance variables have the same name. • The following code snippet shows how to use the this keyword when instance and formal parameters have the same name: Book(int bcode, double bprice) { this.bcode=bcode; this.bprice=bprice; } In the above code snippet, this keyword refers to the instance variables, bcode and bprice. The values of the formal parameters, bcode and bprice of the Book() constructor are assigned to the instance variables. ©NIIT Collaborate Lesson 1C / Slide 6 of 23
  • 7. Collaborate The super and this Keywords (Contd.) • The this Keyword (Contd.) • In addition, you can use the this keyword in a constructor of a class to invoke another constructor of the class. • Unlike the super keyword, the this keyword can invoke the constructor of the same class. • The following code snippet shows how to invoke a constructor using the this keyword: class Book { public Book(String bname) { this(bname, 1001); } public Book(String bname, int bcode) { bookName=bname; bookCode=bcode; } } ©NIIT Collaborate Lesson 1C / Slide 7 of 23
  • 8. Collaborate The Nested try-catch Block • The try-catch block is used to handle exceptions in Java applications. • You can enclose a try-catch block in an existing try-catch block. • The enclosed try-catch block is called the inner try-catch block, and the enclosing block is called the outer try-catch block. • If the inner try block does not contain the catch statement to handle an exception then the catch statement in the outer block is checked for the exception handler. • The following syntax shows how to create a nested try-catch block: class SuperClass { public static void main(String a[]) { <code>; try { ©NIIT Collaborate Lesson 1C / Slide 8 of 23
  • 9. Collaborate The Nested try-catch Block (Contd.) • The following syntax shows how to create a nested try-catch block: (Contd.) <code>; try { <code>; } catch(<exception_name> <var>) { <code>; } } catch(<exception_name> <var>) { <code>; } } } ©NIIT Collaborate Lesson 1C / Slide 9 of 23
  • 10. Collaborate From the Expert’s Desk In this section, you will learn: • Best practices on: • The Use of final Keyword • Tips on: • The Use of Constructors • The finally Block • FAQs ©NIIT Collaborate Lesson 1C / Slide 10 of 23
  • 11. Collaborate Best Practices The Use of final Keyword • The final keyword can be used with: • A variable • A method • A class • The use of the final keyword prevents you from changing the value of a variable. • When you use the final keyword with a variable, the variable acts as a constant. • It is recommended that you name the final variable in uppercase. ©NIIT Collaborate Lesson 1C / Slide 11 of 23
  • 12. Collaborate Best Practices The Use of final Keyword (Contd.) • The syntax to declare the final variable is: final int MY_VAR=10; In the above syntax, the MY_VAR variable is declared as final. As a result, the value of the variable cannot be modified. • The final keyword is used with methods and classes to prevent method and class overriding while implementing inheritance in a Java application. • If a method in a subclass has the same name as the final method in a superclass, a compile time error is generated. ©NIIT Collaborate Lesson 1C / Slide 12 of 23
  • 13. Collaborate Best Practices The Use of final Keyword (Contd.) • The following syntax shows how to declare the final method: class SuperClass { final void finalMethod() {} } • Similarly, if a class is declared final, you cannot extend that class. • If you extend the final class, a compile time error is generated. ©NIIT Collaborate Lesson 1C / Slide 13 of 23
  • 14. Collaborate Best Practices The Use of final Keyword (Contd.) • The following syntax shows how to declare the final class: final class SuperClass { //This is a final class. } In the preceding syntax, the SuperClass class is declared as final. ©NIIT Collaborate Lesson 1C / Slide 14 of 23
  • 15. Collaborate Tips The Use of Constructors • Consider a Java application that contains multiple classes. Each class is extended from another class in the application and contains a default constructor. • When the application is executed, the constructors are called in the order in which the classes are defined. • For example, there are three classes in a Java application: Class1, Class2, and Class3. Class2 extends Class1, and Class3 extends Class2. When you create an instance of Class 3, the constructors are called in the following order: • Class1 constructor • Class2 constructor • Class3 constructor ©NIIT Collaborate Lesson 1C / Slide 15 of 23
  • 16. Collaborate Tips The finally Block • The finally block associated with a try block is executed after the try or catch block is completed. • It is optional to associate the finally block with a try block, but if the try block does not have a corresponding catch block, you should provide the finally block. ©NIIT Collaborate Lesson 1C / Slide 16 of 23
  • 17. Collaborate FAQs • Can classes inherit from more than one class in Java? No, a class cannot be inherited from more than one class in Java. A class is inherited from a single class only. However, multi-level inheritance is possible in Java. For example, if class B extends class A and class C extends class B, class C automatically inherits the properties of class A. • What is the difference between an interface and a class? Both, class and interface, contain constants and methods. A class not only defines methods but also provides their implementation. However, an interface only defines the methods, which are implemented by the class that implements the interface. ©NIIT Collaborate Lesson 1C / Slide 17 of 23
  • 18. Collaborate FAQs (Contd.) • Do you have to catch all types of exceptions that might be thrown by Java? Yes, you can catch all types of exceptions that are thrown in a Java application using the Exception class. • How many exceptions can you associate with a single try block? There is no limit regarding the number of exceptions that can be associated with a single try block. All the exceptions associated with a try block should be handled using multiple catch blocks. ©NIIT Collaborate Lesson 1C / Slide 18 of 23
  • 19. Collaborate FAQs (Contd.) • What are the disadvantages of inner classes? The inner classes have various disadvantages. The use of inner class increases the total number of classes in your code. The Java developers also find it difficult to understand to implement the concept of inner class within the programs. • What is the level of nesting for classes in Java? There is no limit of nesting classes in Java. ©NIIT Collaborate Lesson 1C / Slide 19 of 23
  • 20. Collaborate Challenge 1. You can access particular constructors in the superclass using ______operator. 2. Which of the following exceptions is raised when a number is divided by zero: a. NullPointerException b. ArithmeticException c. ArrayIndexOutOfBoundsException d. NumberFormatException 3. You can have more than one finally block for an exception-handler. (True/False) 4. Match the following: a. public 1. Ensures the value is not changed in the classes that implement an interface. b. static 2. Ensures that are able to override the data members in unrelated classes. c. final 3. Ensures that you cannot create an object of the interface. ©NIIT Collaborate Lesson 1C / Slide 20 of 23
  • 21. Collaborate Challenge (Contd.) 1. The following code is a jumbled code. Rearrange the following code to make it executable: public class Excp { public static void main(String args []) { int num1, num2, num3; num1 = 10; num2 = 0; catch(ArithmeticException e) { System.out.println(" Error Message"); } try { num3 = num1/num2; } ©NIIT Collaborate Lesson 1C / Slide 21 of 23
  • 22. Collaborate Solutions to Challenge • dot • b. ArithmeticException • False • a. 2 b. 1 c. 3 5.      public class Excp { public static void main(String args []) { int num1, num2, num3; num1 = 10; num2 = 0; ©NIIT Collaborate Lesson 1C / Slide 22 of 23
  • 23. Collaborate Solutions to Challenge (Contd.) try { num3 = num1/num2; } catch( ArithmeticException e) { System.out.println(" Error Message"); } ©NIIT Collaborate Lesson 1C / Slide 23 of 23