SlideShare a Scribd company logo
1 of 44
 Decision Making
 Object Oriented Fundamentals
 Inner Classes
 Exception Handling
In this chapter we will:
discuss the use of decision making in
computer programming
describe the use of the Java if and switch
statements
Ensures that a statement is executed only
when a condition is true
Conditions typically involve comparison of
variables or quantities for equality or inequality
Example:
if (age >= 18)
out.println(“You are eligible to vote.”);
An if statement may have an optional else
clause that will only be executed when the
condition is false
Example:
if (wages <= 57600)
tax = 0.124 * wages;
else
tax = 0.124 * 57600;
 Used to accomplish multi-way branching based on the
value of an integer selector variable
 Example:
switch (numberOfPassengers) {
case 0: out.println(“The Harley”);
break;
case 1: out.println(“The Dune Buggy”);
break;
default: out.println(“The Humvee”);
}
What is Access Specifier?
A mechanism to set access levels for classes, attributes, variables, methods and
constructors. The four access levels are:
//In increasing order of accessibility
• PRIVATE - Visible to the same class only.
• DEFAULT - Visible to the same package. No modifiers are needed.
• PROTECTED - Visible to the package and all subclasses.
• PUBLIC - Visible to the world.
ACCESS SPECIFIERS in JAVA
public class Student {
private String course;
public void setCourse(String courseNew) {
this.course = courseNew;
}
public String getCourse() {
return this.course;
}
}
Within a method/constructor, this is a reference to the current object — the
object whose method/constructor is being called.
this KEYWORD in JAVA
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b){
x = a;
y = b;
}
}
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
Technical Definition:
Encapsulation is the technique of making the fields in a class private
and providing access to the fields via public methods.
ENCAPSULATION
If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class. For this reason,
encapsulation is also referred to as data hiding.
ENCAPSULATION - EXAMPLE
1. class Student{
2. private String name;
3. public String getName(){
4. return name;
5. }
6. public void setName(String newName){
7. name = newName;
8. }
9. }
10.class Execute{
11. public static void main(String args[]){
12. String localName;
13. Student s1 = new Student();
14. localName = s1.getName();
15. }
16.}
At line no14, we can not write localName = s1.name;
The public methods are the access points
to a class's private fields(attributes) from
the outside class.
Technical Definition:
Inheritance can be defined as the process where one object (or class)
acquires the properties of another (object or class).
With the use of inheritance the information is made manageable in a
hierarchical order.
INHERITANCE
ANIMAL
MAMMEL
DOG
REPTILE
INHERITANCE
 In programming, inheritance is brought by using the keyword
EXTENDS
 In theory, it is identified using the keyword IS-A.
 By using these keywords we can make one object acquire the
properties of another object.
This is how the extends keyword is used to achieve
inheritance.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
INHERITANCE
Now, based on the above example, In Object Oriented terms, the
following are true:
• Animal is the superclass of Mammal class.
• Animal is the superclass of Reptile class.
• Mammal and Reptile are subclasses of Animal class.
• Dog is the subclass of both Mammal and Animal classes.
Alternatively, if we consider the IS-A relationship, we can say:
• Mammal IS-A Animal
• Reptile IS-A Animal
• Dog IS-A Mammal
Hence : Dog IS-A Animal as well
OVERRIDING
The process of defining a method in child class with the same name &
signature as that of a method already present in parent class.
 If a class inherits a method from its super class, then there is a
chance to override the method provided that it is not marked
final.
 Benefit: A subclass can implement a parent class method based
on its requirement.
 In object-oriented terms, overriding means to override the
functionality of an existing method.
OVERRIDING: USING THE SUPER KEYWORD
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
class TestDog{
public static void main(String args[]){
Animal b = new Dog();
// Animal reference but Dog object
b.move();
//Runs the method in Dog class
}
}
When invoking a superclass version of an
overridden method the super keyword is
used.
This would produce the following
result:
Animals can move
Dogs can walk and run
POLYMORPHISM
CASE I: METHOD POLYMORPHISM
We can have multiple methods with the same name in the same /
inherited / extended class.
There are three kinds of such polymorphism (methods):
1. Overloading: Two or more methods with different
signatures, in the same class.
2. Overriding: Replacing a method of BASE class with
another (having the same signature) in
CHILD class.
3. Polymorphism by implementing Interfaces.
POLYMORPHISM = 1 METHOD/OBJECT HAVING MANY
FORMS/ROLES
POLYMORPHISM – METHOD OVERLOADING
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) {
System.out.println("double d = " + d);
}
}
OUTPUT:
int i = 5
double d = 5.0
Please note that the signature of overloaded
method is different.
POLYMORPHISM – CONSTRUCTOR
OVERLOADING
This example displays the way of overloading a constructor and a
method depending on type and number of parameters.
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is "
+ i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height
+ " feet tall");
}
void info(String s) {
System.out.println(s + ": House is “ + height + " feet
tall");
}
}
What is an Abstract class?
Superclasses are created through the process called
"generalization"
Often, the superclass does not have a "meaning" or does not
directly relate to a "thing" in the real world
Abstract classes cannot be instantiated
Defining Abstract Methods
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
public abstract class Transaction
{
public abstract int computeValue();
public class RetailSale extends Transaction
{
public int computeValue()
{
[...]
Transaction
- computeValue(): int
RetailSale
- computeValue(): int
StockTrade
- computeValue(): int
public class StockTrade extends Transaction
{
public int computeValue()
{
[...]
Note: no implementation
What is an Interface?
• All methods defined in an interface are abstract. Interfaces
can contain no implementation
• Interfaces are declared using the "interface" keyword
• Interfaces are more abstract than abstract classes
• Interfaces are implemented by classes using the
"implements" keyword.
Declaring an Interface
public interface Steerable
{
public void turnLeft(int degrees);
public void turnRight(int degrees);
}
In Steerable.java:
public class Car extends Vehicle implements Steerable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
In Car.java:
When a class "implements" an
interface, the compiler ensures that
it provides an implementation for
all methods defined within the
interface.
27
 Inner classes are classes defined within other classes
 The class that includes the inner class is called the outer class
 There is no particular location where the definition of the inner class
(or classes) must be place within the outer class
 Placing it first or last, however, will guarantee that it is easy to find
28
public class Outer
{
private class Inner
{
// inner class instance variables
// inner class methods
} // end of inner class definition
// outer class instance variables
// outer class methods
}
29
 If an inner class is marked public, then it can
be used outside of the outer class
 In the case of a non-static inner class, it must
be created using an object of the outer class
BankAccount account = new BankAccount();
BankAccount.Money amount =
account.new Money("41.99");
30
 In the case of a static inner class, the procedure is similar to,
but simpler than, that for nonstatic inner classes
OuterClass.InnerClass innerObject =
new OuterClass.InnerClass();
 Note that all of the following are acceptable
innerObject.nonstaticMethod();
innerObject.staticMethod();
OuterClass.InnerClass.staticMethod();
 A class can have as many inner classes as it needs.
 Inner classes have access to each other’s private members as
long as an object of the other inner class is used as the calling
object.
31
32
 It is legal to nest inner classes within inner classes
 The rules are the same as before, but the names get longer
 Given class A, which has public inner class B, which has
public inner class C, then the following is valid:
A aObject = new A();
A.B bObject = aObject.new B();
A.B.C cObject = bObject.new C();
33
 If an object is to be created, but there is no need to name the
object's class, then an anonymous class definition can be
used
 The class definition is embedded inside the expression with
the new operator
34
Exceptions
➔ An "exceptional condition" that alters the normal program flow
➔ Derive from class Exception
➔ Exception is said to be "thrown" and an Exception Handler "catches" it
➔ Includes File Not Found, Network connection was lost, etc.
Errors
➔ Represent unusual situations that are not caused by, and are external
to, the application
➔ Application won't be able to recover from an Error, so these aren't
required to handle
➔ Includes JVM running out of memory, hardware error, etc
Types of Exceptions
➔ Checked Exceptions
◆ Checked at compile time
◆ Must be either handled or
specified using throws keyword
➔ Unchecked Exceptions
◆ Not checked at compile time
◆ Also called as Runtime Exceptions
Checked Exception Example
➔ import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("a.txt");
BufferedReader fileInput = new BufferedReader(file);
}
}
➔ Compilation Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown
at Main.main(Main.java:5)
Runtime Exception Example
➔ class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
➔ Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
try-catch blocks
➔ try block :
◆ Used to enclose the code that might throw an exception.
◆ Must be used within the method.
◆ Java try block must be followed by either catch or finally block.
➔ catch block
◆ Java catch block is used to handle the Exception. It must be used after the
try block only.
◆ You can use multiple catch block with a single try.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){
}
Example
public class Testtrycatch{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("Executing rest of the code...");
}
}
Output :
Exception in thread main java.lang.ArithmeticException:/ by zero
Executing rest of the code...
finally block
➔ Follows a try block.
➔ Always executes, whether or not an exception has occurred.
➔ Allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
➔ Executes right before the return executes present in try block.
Syntax of try-finally block:
try{
// Protected Code that may throw exception
}catch(Exception ex){
// Catch block may or may not execute
}finally{
// The finally block always executes.
}
Advantages of Exception Handling
➔ To maintain the normal flow of the application
➔ Separating Error-Handling Code from "Regular" Code
➔ Propagating Errors Up the Call Stack
➔ Grouping and Differentiating Error Types
Core java oop

More Related Content

What's hot (20)

Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Java02
Java02Java02
Java02
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Object and class
Object and classObject and class
Object and class
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 

Viewers also liked

Viewers also liked (6)

Naukri.com
Naukri.comNaukri.com
Naukri.com
 
Budget 2017-18
Budget 2017-18Budget 2017-18
Budget 2017-18
 
Budget 2017 18
Budget 2017 18Budget 2017 18
Budget 2017 18
 
Bhim app
Bhim appBhim app
Bhim app
 
Union Budget 2017-18
Union Budget 2017-18Union Budget 2017-18
Union Budget 2017-18
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 

Similar to Core java oop

Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
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
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in javaAtul Sehdev
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
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.pptxRudranilDas11
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 

Similar to Core java oop (20)

Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap11
Chap11Chap11
Chap11
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
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
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Inheritance
InheritanceInheritance
Inheritance
 
Hemajava
HemajavaHemajava
Hemajava
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
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
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 

Recently uploaded

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
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
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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
 
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
 
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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
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
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Core java oop

  • 1.
  • 2.  Decision Making  Object Oriented Fundamentals  Inner Classes  Exception Handling
  • 3.
  • 4. In this chapter we will: discuss the use of decision making in computer programming describe the use of the Java if and switch statements
  • 5. Ensures that a statement is executed only when a condition is true Conditions typically involve comparison of variables or quantities for equality or inequality Example: if (age >= 18) out.println(“You are eligible to vote.”);
  • 6.
  • 7. An if statement may have an optional else clause that will only be executed when the condition is false Example: if (wages <= 57600) tax = 0.124 * wages; else tax = 0.124 * 57600;
  • 8.  Used to accomplish multi-way branching based on the value of an integer selector variable  Example: switch (numberOfPassengers) { case 0: out.println(“The Harley”); break; case 1: out.println(“The Dune Buggy”); break; default: out.println(“The Humvee”); }
  • 9.
  • 10. What is Access Specifier? A mechanism to set access levels for classes, attributes, variables, methods and constructors. The four access levels are: //In increasing order of accessibility • PRIVATE - Visible to the same class only. • DEFAULT - Visible to the same package. No modifiers are needed. • PROTECTED - Visible to the package and all subclasses. • PUBLIC - Visible to the world. ACCESS SPECIFIERS in JAVA public class Student { private String course; public void setCourse(String courseNew) { this.course = courseNew; } public String getCourse() { return this.course; } }
  • 11. Within a method/constructor, this is a reference to the current object — the object whose method/constructor is being called. this KEYWORD in JAVA public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b){ x = a; y = b; } } public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y){ this.x = x; this.y = y; } }
  • 12. Technical Definition: Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. ENCAPSULATION If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
  • 13. ENCAPSULATION - EXAMPLE 1. class Student{ 2. private String name; 3. public String getName(){ 4. return name; 5. } 6. public void setName(String newName){ 7. name = newName; 8. } 9. } 10.class Execute{ 11. public static void main(String args[]){ 12. String localName; 13. Student s1 = new Student(); 14. localName = s1.getName(); 15. } 16.} At line no14, we can not write localName = s1.name; The public methods are the access points to a class's private fields(attributes) from the outside class.
  • 14. Technical Definition: Inheritance can be defined as the process where one object (or class) acquires the properties of another (object or class). With the use of inheritance the information is made manageable in a hierarchical order. INHERITANCE ANIMAL MAMMEL DOG REPTILE
  • 15. INHERITANCE  In programming, inheritance is brought by using the keyword EXTENDS  In theory, it is identified using the keyword IS-A.  By using these keywords we can make one object acquire the properties of another object. This is how the extends keyword is used to achieve inheritance. public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ } public class Dog extends Mammal{ }
  • 16. INHERITANCE Now, based on the above example, In Object Oriented terms, the following are true: • Animal is the superclass of Mammal class. • Animal is the superclass of Reptile class. • Mammal and Reptile are subclasses of Animal class. • Dog is the subclass of both Mammal and Animal classes. Alternatively, if we consider the IS-A relationship, we can say: • Mammal IS-A Animal • Reptile IS-A Animal • Dog IS-A Mammal Hence : Dog IS-A Animal as well
  • 17. OVERRIDING The process of defining a method in child class with the same name & signature as that of a method already present in parent class.  If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final.  Benefit: A subclass can implement a parent class method based on its requirement.  In object-oriented terms, overriding means to override the functionality of an existing method.
  • 18. OVERRIDING: USING THE SUPER KEYWORD class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } class TestDog{ public static void main(String args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class } } When invoking a superclass version of an overridden method the super keyword is used. This would produce the following result: Animals can move Dogs can walk and run
  • 19. POLYMORPHISM CASE I: METHOD POLYMORPHISM We can have multiple methods with the same name in the same / inherited / extended class. There are three kinds of such polymorphism (methods): 1. Overloading: Two or more methods with different signatures, in the same class. 2. Overriding: Replacing a method of BASE class with another (having the same signature) in CHILD class. 3. Polymorphism by implementing Interfaces. POLYMORPHISM = 1 METHOD/OBJECT HAVING MANY FORMS/ROLES
  • 20. POLYMORPHISM – METHOD OVERLOADING class Test { public static void main(String args[]) { myPrint(5); myPrint(5.0); } static void myPrint(int i) { System.out.println("int i = " + i); } static void myPrint(double d) { System.out.println("double d = " + d); } } OUTPUT: int i = 5 double d = 5.0 Please note that the signature of overloaded method is different.
  • 21. POLYMORPHISM – CONSTRUCTOR OVERLOADING This example displays the way of overloading a constructor and a method depending on type and number of parameters. class MyClass { int height; MyClass() { System.out.println("bricks"); height = 0; } MyClass(int i) { System.out.println("Building new House that is " + i + " feet tall"); height = i; } void info() { System.out.println("House is " + height + " feet tall"); } void info(String s) { System.out.println(s + ": House is “ + height + " feet tall"); } }
  • 22. What is an Abstract class? Superclasses are created through the process called "generalization" Often, the superclass does not have a "meaning" or does not directly relate to a "thing" in the real world Abstract classes cannot be instantiated
  • 23. Defining Abstract Methods Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public abstract class Transaction { public abstract int computeValue(); public class RetailSale extends Transaction { public int computeValue() { [...] Transaction - computeValue(): int RetailSale - computeValue(): int StockTrade - computeValue(): int public class StockTrade extends Transaction { public int computeValue() { [...] Note: no implementation
  • 24. What is an Interface? • All methods defined in an interface are abstract. Interfaces can contain no implementation • Interfaces are declared using the "interface" keyword • Interfaces are more abstract than abstract classes • Interfaces are implemented by classes using the "implements" keyword.
  • 25. Declaring an Interface public interface Steerable { public void turnLeft(int degrees); public void turnRight(int degrees); } In Steerable.java: public class Car extends Vehicle implements Steerable { public int turnLeft(int degrees) { [...] } public int turnRight(int degrees) { [...] } In Car.java: When a class "implements" an interface, the compiler ensures that it provides an implementation for all methods defined within the interface.
  • 26.
  • 27. 27  Inner classes are classes defined within other classes  The class that includes the inner class is called the outer class  There is no particular location where the definition of the inner class (or classes) must be place within the outer class  Placing it first or last, however, will guarantee that it is easy to find
  • 28. 28 public class Outer { private class Inner { // inner class instance variables // inner class methods } // end of inner class definition // outer class instance variables // outer class methods }
  • 29. 29  If an inner class is marked public, then it can be used outside of the outer class  In the case of a non-static inner class, it must be created using an object of the outer class BankAccount account = new BankAccount(); BankAccount.Money amount = account.new Money("41.99");
  • 30. 30  In the case of a static inner class, the procedure is similar to, but simpler than, that for nonstatic inner classes OuterClass.InnerClass innerObject = new OuterClass.InnerClass();  Note that all of the following are acceptable innerObject.nonstaticMethod(); innerObject.staticMethod(); OuterClass.InnerClass.staticMethod();
  • 31.  A class can have as many inner classes as it needs.  Inner classes have access to each other’s private members as long as an object of the other inner class is used as the calling object. 31
  • 32. 32  It is legal to nest inner classes within inner classes  The rules are the same as before, but the names get longer  Given class A, which has public inner class B, which has public inner class C, then the following is valid: A aObject = new A(); A.B bObject = aObject.new B(); A.B.C cObject = bObject.new C();
  • 33. 33  If an object is to be created, but there is no need to name the object's class, then an anonymous class definition can be used  The class definition is embedded inside the expression with the new operator
  • 34. 34
  • 35.
  • 36. Exceptions ➔ An "exceptional condition" that alters the normal program flow ➔ Derive from class Exception ➔ Exception is said to be "thrown" and an Exception Handler "catches" it ➔ Includes File Not Found, Network connection was lost, etc. Errors ➔ Represent unusual situations that are not caused by, and are external to, the application ➔ Application won't be able to recover from an Error, so these aren't required to handle ➔ Includes JVM running out of memory, hardware error, etc
  • 37. Types of Exceptions ➔ Checked Exceptions ◆ Checked at compile time ◆ Must be either handled or specified using throws keyword ➔ Unchecked Exceptions ◆ Not checked at compile time ◆ Also called as Runtime Exceptions
  • 38. Checked Exception Example ➔ import java.io.*; class Main { public static void main(String[] args) { FileReader file = new FileReader("a.txt"); BufferedReader fileInput = new BufferedReader(file); } } ➔ Compilation Error: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at Main.main(Main.java:5)
  • 39. Runtime Exception Example ➔ class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } ➔ Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) Java Result: 1
  • 40. try-catch blocks ➔ try block : ◆ Used to enclose the code that might throw an exception. ◆ Must be used within the method. ◆ Java try block must be followed by either catch or finally block. ➔ catch block ◆ Java catch block is used to handle the Exception. It must be used after the try block only. ◆ You can use multiple catch block with a single try. Syntax of java try-catch try{ //code that may throw exception }catch(Exception_class_Name ref){ }
  • 41. Example public class Testtrycatch{ public static void main(String args[]){ try{ int data=50/0; }catch(ArithmeticException e){ System.out.println(e); } System.out.println("Executing rest of the code..."); } } Output : Exception in thread main java.lang.ArithmeticException:/ by zero Executing rest of the code...
  • 42. finally block ➔ Follows a try block. ➔ Always executes, whether or not an exception has occurred. ➔ Allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. ➔ Executes right before the return executes present in try block. Syntax of try-finally block: try{ // Protected Code that may throw exception }catch(Exception ex){ // Catch block may or may not execute }finally{ // The finally block always executes. }
  • 43. Advantages of Exception Handling ➔ To maintain the normal flow of the application ➔ Separating Error-Handling Code from "Regular" Code ➔ Propagating Errors Up the Call Stack ➔ Grouping and Differentiating Error Types