44
CORE JAVA OOP BY PARTH SHAH

Core java oop

Embed Size (px)

Citation preview

Page 1: Core java oop

CORE JAVA OOPBY PARTH SHAH

Page 2: Core java oop

TOPICS TO BE COVERED Decision Making Object Oriented Fundamentals Inner Classes Exception Handling

Page 3: Core java oop

TOPICDECISION MAKING

Page 4: Core java oop

CHAPTER PREVIEW

In this chapter we will:discuss the use of decision making in computer programming

describe the use of the Java if and switch statements

Page 5: Core java oop

IF STATEMENT

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.”);

Page 6: Core java oop
Page 7: Core java oop

IF STATEMENT WITH OPTIONAL ELSEAn 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;

Page 8: Core java oop

SWITCH STATEMENT 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”);

}

Page 9: Core java oop

OOP FUNDAMENTALS

Page 10: Core java oop

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;

}}

Page 11: Core java oop

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

Page 12: Core java oop

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.

Page 13: Core java oop

ENCAPSULATION - EXAMPLE1. 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.

Page 14: Core java oop

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

Page 15: Core java oop

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

Page 16: Core java oop

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

Page 17: Core java oop

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.

Page 18: Core java oop

OVERRIDING: USING THE SUPER KEYWORDclass Animal{

public void move(){System.out.println("Animals can move");

}}class Dog extends Animal{

public void move(){super.move(); // invokes the super class

methodSystem.out.println("Dogs can walk and

run");}

}class TestDog{

public static void main(String args[]){Animal b = new Dog(); // Animal reference but Dog objectb.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 moveDogs can walk and run

Page 19: Core java oop

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

Page 20: Core java oop

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 = 5double d = 5.0

Please note that the signature of overloaded method is different.

Page 21: Core java oop

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"); }}

Page 22: Core java oop

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

Page 23: Core java oop

Defining Abstract Methods

Inheritance is declared using the "extends" keywordIf 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

Page 24: Core java oop

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.

Page 25: Core java oop

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 thatit provides an implementation for all methods defined within theinterface.

Page 26: Core java oop

INNER CLASSES

Page 27: Core java oop

27

SIMPLE USES OF INNER CLASSES 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

Page 28: Core java oop

28

INNER/OUTER CLASSESpublic class Outer{

private class Inner{ // inner class instance variables

// inner class methods

} // end of inner class definition

// outer class instance variables

// outer class methods

}

Page 29: Core java oop

29

PUBLIC INNER CLASSES 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");

Page 30: Core java oop

30

PUBLIC STATIC INNER CLASSES

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 acceptableinnerObject.nonstaticMethod();innerObject.staticMethod();OuterClass.InnerClass.staticMethod();

Page 31: Core java oop

31

MULTIPLE INNER CLASSES 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.

Page 32: Core java oop

32

NESTING INNER CLASSES 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();

Page 33: Core java oop

33

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

Page 34: Core java oop

34

ANONYMOUS CLASSES

Page 35: Core java oop

EXCEPTION HANDELING

Page 36: Core java oop

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

Page 37: Core java oop

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

Page 38: Core java oop

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)

Page 39: Core java oop

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

Page 40: Core java oop

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

}

Page 41: Core java oop

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

Page 42: Core java oop

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.

}

Page 43: Core java oop

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

Page 44: Core java oop