SlideShare a Scribd company logo
Advanced Class Features
Objectives
 Describe static variables, methods and
initializers
 Describe final classes, methods and variables
 Abstract classes and methods
 Inner classes
 Static and non-static inner classes
 interface
The static Keyword
 The static keyword is used as a modifier on
variables and inner classes
 The static keyword declares the attribute or
method is associated with the class as a
whole rather than any particular instance of
that class
 Thus static members are often called as
“class members”
Class Attributes
 Are shared among all instances of a class
public class Count{
private int serialNumber;
public static int counter=0;
public static int getTotalCount(){
return counter;
}
public Count(){
counter++;
serialNumber=counter;
}
}
The static Keyword
 Static method cannot use “this”
 They cannot access any non-static fields
 A static method cannot be overridden
Static Initializers
 A class can contain code in a static block that does
not exist within a method body
 Static code block executes only once when the class
is loaded
 A static block is used to initialize static attributes
public class Count{
public static int counter;
static{
counter=Integer.getInteger(“myCounter”).intValue();
}
}
//use java –DmyCounter=45 Test to execute
The final Keyword
 You cannot subclass a final class
 You cannot override a final method
 A final variable is a constant
 A final variable can only be set once, but that
assignment can occur independently of the
declaration;
 A blank final instance attribute must be set in every
constructor
 A blank final method variable must be set in the method
body before being used
Abstract Classes
 Any class with one or more abstract methods
is called an abstract class
 Abstract class can’t be instantiated
 Abstract classes may have data attributes,
concrete methods and constructors
 It is a good practice to make the constructors
protected
Interfaces
 A public interface is a contract between client code
and the class that implements that interface
 A java interface is a formal declaration of such a
contract in which all methods contain no
implementation
 Many unrelated classes can implement the same
interface
 A class can implement many, unrelated interfaces
Uses of Interfaces
 Declaring methods that one or more classes are
expected to implement
 Determining an object’s programming interface
without revealing the actual body of the class
 Capturing similarities between unrelated classes
without forcing a class relationship
 Simulating multiple inheritance by declaring a class
that implements several interfaces
Inner classes
 Allow a class defintion to be placed inside
another class definition
 Group classes that logically belong together
 Have access to their enclosing class’s scope
Properties of Inner classes
 You can use the class name only within the
defined scope except when used in a
qualified name. The name of the inner class
must differ from the enclosing class
 The inner class can be defined inside a
method. Only local variables marked as final,
can be accessed by methods within an inner
class
Properties of Inner Classes
 The inner class can use both class and
instance variables of enclosing classes and
local variables of enclosing blocks
 The inner class can be defined as abstract
 The inner class can have any access mode
 The inner class can act as an interface
implemented by another inner class
Properties of Inner Classes
 Inner classes that are declared static
automatically become top-level classes
 Inner classes cannot declare any static
members
 An inner class wanting to use a static
member must be declared static
Exceptions
Objectives
 Define Exceptions
 Use try, catch, and finally statements
 Describe exception categories
 Identify common exceptions
 Develop programs to handle your own
exceptions
Exceptions
 The Exception class defines error conditions that
your program encounters
 Exception can occur when
 The file you try to open does not exist
 The network connection is disrupted
 Operands being manipulated are out of prescribed ranges
 The class file you are interested in loading is missing
 An error class defines serious (fatal) error
conditions
try and catch statements
try{
//code that might throw a particular exception
}catch(MyException myExcept){
//code to execute if a MyExceptiontype is thrown
}
catch(Exception otherExcept){
//Code to execute if a general Exception is
//thrown
}
Call Stack Mechanism
 If an exception is not handled in the current
try-catch block, it is thrown to the caller of
that method
 If the exception gets back to the main
method and is not handled there, the program
is terminated abnormally
finally statement
try{
startFaucet();
waterLawn();
}catch(BrokenPipeException e){
logProblem(e);
}finally{
stopFaucet();
}
Exception Categories
StackO verflow E rror O utO fM em oryError
V irtualM achineError AW T E rror
Error
Arithm eticE xception N ullPointerE xception IndexO utO fB oundsE xception
R untim eException
E O FException FileN otFoundE xception
IO Exception
E xception
T hrow able
Common Exceptions
 ArithmeticException
 NullPointerException
 NegativeArraySizeException
 ArrayIndexOutOfBoundsException
 SecurityException
The Handle or Declare Rule
 Handle the Exception by using the try-catch-finally
block
 Declare that the code causes an exception by using
the throws clause
 A method may declare that it throws more than one
exception
 You do not need to handle or declare run-time
exceptions or errors
Method Overriding and Exceptions
 Must throw exceptions that are the same class as the
exceptions being thrown by the overridden method
 May throw exceptions that are subclasses of the
exceptions being thrown by the overridden method
 If a superclass method throws multiple exceptions,
the overriding method must throw a proper subset
of exceptions thrown by the overridden method

More Related Content

What's hot

Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
arnold 7490
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
Vipul Naik
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
Shiva Cse
 
Java
JavaJava
Java
mbruggen
 
Java training
Java trainingJava training
Java training
Ducat Education
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
Prem Kumar Badri
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Abishek Purushothaman
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
İbrahim Kürce
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
Non access modifiers
Non access modifiersNon access modifiers
Non access modifiers
Muthukumaran Subramanian
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
Sugavanam Natarajan
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Chap11
Chap11Chap11
Chap11
Terry Yoast
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
parag
 

What's hot (20)

Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
 
Java
JavaJava
Java
 
Java training
Java trainingJava training
Java training
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Non access modifiers
Non access modifiersNon access modifiers
Non access modifiers
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Chap11
Chap11Chap11
Chap11
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
 

Similar to java tutorial 4

Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Gaurav Mehta
 
Java Core
Java CoreJava Core
Java Core
Gaurav Mehta
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
talenttransform
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
ChiradipBhattacharya
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
Haitham El-Ghareeb
 
Core java questions
Core java questionsCore java questions
Core java questions
Pradheep Ayyanar
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
ParvizMirzayev2
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
Raghavendra V Gayakwad
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
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
Jamsher bhanbhro
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
Shashwat Shriparv
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
ParvizMirzayev2
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
Syed Afaq Shah MACS CP
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
Debasish Pratihari
 
The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 

Similar to java tutorial 4 (20)

Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
Java Core
Java CoreJava Core
Java Core
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
Core java questions
Core java questionsCore java questions
Core java questions
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
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
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Java basics
Java basicsJava basics
Java basics
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
 

More from Tushar Desarda

java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
Tushar Desarda
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
Tushar Desarda
 
Database management system
Database management systemDatabase management system
Database management system
Tushar Desarda
 
A database introduction
A database introductionA database introduction
A database introduction
Tushar Desarda
 
C data_structures
C  data_structuresC  data_structures
C data_structures
Tushar Desarda
 

More from Tushar Desarda (6)

java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Database management system
Database management systemDatabase management system
Database management system
 
A database introduction
A database introductionA database introduction
A database introduction
 
C data_structures
C  data_structuresC  data_structures
C data_structures
 

Recently uploaded

Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 

Recently uploaded (20)

Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 

java tutorial 4

  • 2. Objectives  Describe static variables, methods and initializers  Describe final classes, methods and variables  Abstract classes and methods  Inner classes  Static and non-static inner classes  interface
  • 3. The static Keyword  The static keyword is used as a modifier on variables and inner classes  The static keyword declares the attribute or method is associated with the class as a whole rather than any particular instance of that class  Thus static members are often called as “class members”
  • 4. Class Attributes  Are shared among all instances of a class public class Count{ private int serialNumber; public static int counter=0; public static int getTotalCount(){ return counter; } public Count(){ counter++; serialNumber=counter; } }
  • 5. The static Keyword  Static method cannot use “this”  They cannot access any non-static fields  A static method cannot be overridden
  • 6. Static Initializers  A class can contain code in a static block that does not exist within a method body  Static code block executes only once when the class is loaded  A static block is used to initialize static attributes public class Count{ public static int counter; static{ counter=Integer.getInteger(“myCounter”).intValue(); } } //use java –DmyCounter=45 Test to execute
  • 7. The final Keyword  You cannot subclass a final class  You cannot override a final method  A final variable is a constant  A final variable can only be set once, but that assignment can occur independently of the declaration;  A blank final instance attribute must be set in every constructor  A blank final method variable must be set in the method body before being used
  • 8. Abstract Classes  Any class with one or more abstract methods is called an abstract class  Abstract class can’t be instantiated  Abstract classes may have data attributes, concrete methods and constructors  It is a good practice to make the constructors protected
  • 9. Interfaces  A public interface is a contract between client code and the class that implements that interface  A java interface is a formal declaration of such a contract in which all methods contain no implementation  Many unrelated classes can implement the same interface  A class can implement many, unrelated interfaces
  • 10. Uses of Interfaces  Declaring methods that one or more classes are expected to implement  Determining an object’s programming interface without revealing the actual body of the class  Capturing similarities between unrelated classes without forcing a class relationship  Simulating multiple inheritance by declaring a class that implements several interfaces
  • 11. Inner classes  Allow a class defintion to be placed inside another class definition  Group classes that logically belong together  Have access to their enclosing class’s scope
  • 12. Properties of Inner classes  You can use the class name only within the defined scope except when used in a qualified name. The name of the inner class must differ from the enclosing class  The inner class can be defined inside a method. Only local variables marked as final, can be accessed by methods within an inner class
  • 13. Properties of Inner Classes  The inner class can use both class and instance variables of enclosing classes and local variables of enclosing blocks  The inner class can be defined as abstract  The inner class can have any access mode  The inner class can act as an interface implemented by another inner class
  • 14. Properties of Inner Classes  Inner classes that are declared static automatically become top-level classes  Inner classes cannot declare any static members  An inner class wanting to use a static member must be declared static
  • 16. Objectives  Define Exceptions  Use try, catch, and finally statements  Describe exception categories  Identify common exceptions  Develop programs to handle your own exceptions
  • 17. Exceptions  The Exception class defines error conditions that your program encounters  Exception can occur when  The file you try to open does not exist  The network connection is disrupted  Operands being manipulated are out of prescribed ranges  The class file you are interested in loading is missing  An error class defines serious (fatal) error conditions
  • 18. try and catch statements try{ //code that might throw a particular exception }catch(MyException myExcept){ //code to execute if a MyExceptiontype is thrown } catch(Exception otherExcept){ //Code to execute if a general Exception is //thrown }
  • 19. Call Stack Mechanism  If an exception is not handled in the current try-catch block, it is thrown to the caller of that method  If the exception gets back to the main method and is not handled there, the program is terminated abnormally
  • 21. Exception Categories StackO verflow E rror O utO fM em oryError V irtualM achineError AW T E rror Error Arithm eticE xception N ullPointerE xception IndexO utO fB oundsE xception R untim eException E O FException FileN otFoundE xception IO Exception E xception T hrow able
  • 22. Common Exceptions  ArithmeticException  NullPointerException  NegativeArraySizeException  ArrayIndexOutOfBoundsException  SecurityException
  • 23. The Handle or Declare Rule  Handle the Exception by using the try-catch-finally block  Declare that the code causes an exception by using the throws clause  A method may declare that it throws more than one exception  You do not need to handle or declare run-time exceptions or errors
  • 24. Method Overriding and Exceptions  Must throw exceptions that are the same class as the exceptions being thrown by the overridden method  May throw exceptions that are subclasses of the exceptions being thrown by the overridden method  If a superclass method throws multiple exceptions, the overriding method must throw a proper subset of exceptions thrown by the overridden method