Oop Sum

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Main diagram of programming

Structured programming  loop , if , …. in main ‫اﻟﻛود اﻟﻌﺎدي‬


Procedural programming  Many of methods Call themselves
Object oriented programming  Class And Objects
Object-oriented programming is an extension of procedural
programming and structured programming

Class
‫ﯾﺗﻛون ﻣن ﺟزﺋﯾن ﻣﮭﻣﯾن ھﻣﺎ اﻟداﺗﺎ و اﻟﻣﯾﺛود‬
1)State: data fields with their current values (attributes).
1) Behavior: methods of an object (actions).
UML

#  protected
_  private
+  Public
Ahmed  Static

Constructor
Can’t Use void with constructor ??
‫} اﻟﻛوﻧﺳﺗراﻛور ﻣﯾﻧﻔﻌش ﯾﻛون ﻟﮫ‬
Return type
Void --> return nothing ;}
If a class has no constructor, Java gives it a default constructor with no
parameters that sets all fields to default values
Number  zero
Bool  false
String  null

‫ﺑﯾﻛون ﻓﯾﮫ ﻛوﻧﺳﺗراﻛﺗور ﻣﺑدﺋﻲ ﻟو اﻧﺎ ﻣﻌﻣﻠﺗش اي واﺣد ﻓﻲ اﻟﻛﻼس ﺑﯾﺗﻌﻣل ﺗﻠﻘﺎﺋﻲ ﻣن‬
Compiler

‫اﻟﻛوﻧﺳﺗراﻛﺗور ﺑﯾﺑدا اﻧﮫ ﯾﺷﺗﻐل اول ﻣﺎ اﻋﻣل اوﺑﺟﯾﻛت‬


Book b = new Book();

‫اول ﻣﺎ اﻋﻣل ﻛده أي ﺣﺎﺟﮫ ﻣﻌﻣوﻟﮫ ﺟواه ھﺗﺗﻧﻔذ ﻋﻠطول‬


‫ﻋﻠﻲ ﺣﺳب ﻧوع اﻟﻛوﻧﺳﺗراﻛﺗور ﺑﺷوف ھﺣط اﯾﮫ ﺑﯾن اﻻﻗواس‬
Book b = new Book();-  No argument (Default)
Book b = new Book(“Mostafa”); This take parameter
Note
‫ﻟو ﻋﻣﻠت ﻛوﻧﺳﺗراﻛﺗور ﻣن اﻟﻧوع اﻟﺗﺎﻧﻲ وﻣﻌﻣﻠﺗش واﺣد ﻣن اﻟﻧوع اﻷول ﻣش ھﯾﺗﻌﻣل ﺗﻠﻘﺎﺋﻲ‬
‫ﺑﻣﻌﻧﻲ‬
Public Book(String n){
}
‫اﻧﺎ ﻋﻣﻠت ده ﻓﻘط ﺟوه اﻟﻛﻼس‬
‫ﻟو ﺟﯾت ﻓﻲ ﻋﻣﻠت اﻟﺷﻛل ده‬
Book b = new Book(); ERROR

Note
private n;
Public Book(String n){
n=n; // there are 2 value with same name // you can use this
this.n=n; // correct }
‫‪Constructor Call Constructor With THIS‬‬

‫‪Static‬‬
‫ﺑﺗﮭﺗم ﺑﺎﻟﻛﻼس ﺑﺎﻟﻛﺎﻣل وﻟﯾس اوﺑﺟﻛت ﻣﻧﮫ ﺑﻣﻌﻧﻲ ان أي ﻣﯾﺛود ﻣن اﻟﻧوع ده او داﺗﺎ ﺑﯾﺗﻧﺎدي‬
‫ﻋﻠﯾﮭﺎ ﺑﺎﻟﺷﻛل ده‬
‫‪Classname.StaticMehod‬‬
‫ﻣﺛﺎل وﻧﻘطﮫ ﻣﮭﻣﮫ ‪ :‬ﻟو اﻧﺎ ﻋﻣﻠت ﻓﻲ اﻟﻛوﻧﺳﺗراﻛﺗور اﻧﮫ ﻛل ﻣﺎ ﯾﻌﻣل اوﺑﺟﯾﻛت ﺟدﯾد ھﺣط‬
‫ﻛﺎوﻧﺗر ﯾزﯾد‬
‫;)(‪Book b1 = new Book‬‬
‫;)(‪Book b2= new Book‬‬
‫;)(‪Book b3 = new Book‬‬
‫اﻟﻣﻔروض ﻛده اﻟﻛﺎوﻧﺗر ﺑﺗﺎﻋﻲ ھﯾﺑﻘﻲ ب ‪ 3‬ﻋﺷﺎن ﻋﻣﻠت ‪ 3‬اوﺑﺟﯾﻛت واﻟﻛﺎوﻧﺗر اﻧﺎ ﻋﺎﻣﻠﮫ‬
‫‪Static‬‬
‫;‪ B1.count; Book.count‬اﻟﻘﯾﻣﺗﯾن ھﯾطﺑﻌوا ‪3‬‬

‫‪Important‬‬
‫‪If The method is static then Any variable in the method must be static‬‬
Else won’t be compile

If the method without static then can access Static Variable without any
errors
Static variables and methods can be used from instance or static
methods in the class.
Instance variables and methods can only be used from instance
methods, (i.e., static
Example
Wrong code
Example :
F Static
f instance

Visibility Modifiers
Public  Can access in any another package or class
Private  in only same class
Default ‫ ﻣش ﺑﺣط ﺟﻧب اﻟﻔﺎﻟﯾو أي ﺣﺎﺟﮫ‬ in the same package
Protected  in the same package
Accessing private state •
Client code won't compile if it accesses private fields:

Visibility modifiers are used for the members of the class, not local
variables inside the methods.
• Using a visibility modifier on local variables would cause a
compilation error.
• In most cases, the constructor should be public. – However, if you
want to prohibit the user from creating an instance of a class, you can
use a private constructor

Passing Objects to Methods


• Passing by value for primitive type value (the value is passed to the
parameter)
• Passing by value for reference type value (the value is the reference
to the object)
Arrays of Objects
Point[] points = new Point[3];
Default
Points [0] = null
Points [1] = null
Points [2] = null

Important
You must create object of all Array
Ex:
Inheritance

The protected Modifier #


• The protected modifier can be applied on data and methods in a
class. A protected data or a protected method in a public class can be
accessed by any class in the same package or its subclasses, even if the
subclasses are in a different package.
• private, default, protected, public

ALL DATA IN SUPERCLASS ARE INHERIT IN SUP


Are superclass’s Constructors Inherited? No.
They are not inherited. They are invoked explicitly or implicitly.
• Constructors can only be invoked from the subclasses'
constructors, using the keyword super.
• If the keyword super is not explicitly used, the superclass's
no-arg constructor is automatically invoked by compiler
(implicitly), how?
Take care about what new ?? Parent or subclass
Constructor Chaining Constructing an instance (or object) of a subclass
invokes all the superclasses’ constructors along the inheritance chain.
This is called constructor chaining.
For instance, if class A extends B, and B extends C, when the
constructor of A is invoked, it invokes the constructor of B which
invokes the constructor of C !
EX

CHECK THIS (: //
B's constructor is invoked
A's constructor is invoked

This is because when a subclass constructor is invoked, it implicitly calls the superclass
constructor first, unless the subclass constructor explicitly calls another constructor of
the superclass using the super keyword. In this case, the A class constructor does not
use the super keyword, so it calls the default constructor of the B class, which prints
“B’s constructor is invoked”. Then, the A class constructor prints “A’s constructor is
invoked”.
Important Ex

1. Start from the main method


2. Invoke Faculty constructor
3. Invoke Employee’s no_arg constructor
4. Invoke Employee(String) constructor
5. Invoke Person() constructor
The code defines three classes: Person, Employee and Faculty. Each class
has a constructor, which is a special method that is invoked when an object
of that class is created. The Faculty class extends the Employee class,
which means it inherits all the fields and methods from the Employee
class. The Employee class extends the Person class, which means it
inherits all the fields and methods from the Person class.
The main method in the Faculty class creates a new Faculty object by
calling the no-arg constructor of the Faculty class. This constructor prints
“(4) Faculty’s no-arg constructor is invoked”. However, before executing the
body of this constructor, it implicitly calls the no-arg constructor of its
superclass, which is the Employee class. This constructor prints “(3)
Employee’s no-arg constructor is invoked”. However, before executing the
body of this constructor, it explicitly calls another constructor of the same
class by using the keyword this. This constructor takes a String argument
and prints it. The argument passed to this constructor is “(2) Invoke
Employee’s overloaded constructor”. However, before executing the body
of this constructor, it implicitly calls the no-arg constructor of its
superclass, which is the Person class. This constructor prints “(1) Person’s
no-arg constructor is invoked”.
Therefore, the output of the code shows the order of execution of the
constructors from the superclass to the subclass: Person -> Employee ->
Faculty. This is called constructor chaining in Java

FINALLY THE OUT PUT IS


(1) Person's no-arg constructor is invoked
(2) Invoke Employee’s overloaded constructor
(3) Employee's no-arg constructor is invoked
(4) Faculty's no-arg constructor is invoked
Can these classes be compiled successfully?

Or, can this object new Apple() be created successfully?


Abstract
An abstract class cannot be used to create objects.
An abstract class can contain abstract methods that are implemented in concrete
subclasses.
Abstract method: a method that does not have a body! can only be used in
abstract class.
Abstract method

an abstract function can’t be final.

You can inherit from only one Abstract class


Abstract method has no implementation.
Constructors cannot be defined with abstract keyword
Static Method cannot be declared as abstract(static
method cannot be overridden)
Access modifiers can be added to abstract methods
and classes (optional)
Syntax for abstract method
abstract return_type method_name ( argument-list );
// ‫اﻟﺗرﺗﯾب ﯾﻔرق ﻓﻲ طرﯾﻖ ﻛﺗﺎﺑﮫ اﻟﻣﯾﺛود‬
public abstract double calculateArea( ) ;

‫ﺑﺎﺧﺗﺻﺎر ﺑﺳﺗﺧدم اﻻﺑﺳﺗراﻛت ﻟﻣﺎ ﯾﻛون ﻋﻧدي ﺣﺎﺟﮫ ﻋﺎﻣﮫ وھﺑدا اﺧﺻﺻﮭﺎ ﻟﻛل‬
‫ﺳب ﻛﻼس‬
‫ﻟﻣﺎ اﻋﻣل اﻧﮭﯾرت ﻣﻧﮭم ھﻛون ﻣﺿطر اﻧﻲ اﻋﻣل ﻧﻔس اﻟﻣﯾﺛود ﺑﻧﻔس اﻟﺑراﻣﯾﺗر وﻟﻛن ﻣﻣﻛن ﻛل واﺣد ﯾﻛون‬
‫ﻟﯾﮭﺎ اﻣر ﻣﺧﺗﻠف ﻋن اﻟﺗﺎﻧﯾﮫ‬
‫ﻣﺛﺎل اﺧر‬

‫اﻟﺷﻛل دي ﺣﺎﺟﮫ ﻋﺎﻣﮫ وﻟﯾﮭم ﻣﺳﺎﺣﮫ وﻣﺣﯾط ﺑس اﻟﻣﺳﺗطﯾل ﻏﯾر اﻟﻣرﺑﻊ وھﻛذا‬
‫‪Notes‬‬
‫ﻣﯾﻧﻔﻌش ﺗﺎﺧد اوﺑﺟﻛت ﻣن اﺑﺳﺗراﻛت ﻛﻼس •‬
‫ﻟو ﻋﻣﻠت اﻧﮭﯾرت ﻟﻛﻼس ﺟواه اﺑﺳﺗراﻛت ﻣﯾﺛود ﻻزم ﺗﻛﺗب ﻧﻔس اﻟﻣﯾﺛود ﺑﻧﻔس اﻟﺷﻛل ﻋﺷﺎن ﻣﯾﻛون ﻓﯾﮫ‬
‫اﯾرور ﻓﻲ اﻟﻛﻼس‬
‫ﻟو اﻟﻛﻼس ﻧﻔﺳﮫ اﺑﺳﺗراﻛت واﻟﻣﯾﺛود ﻻ ﻋﺎدي ﻣﻣﻛن ﻣﻌﻣﻠش اوﻓررﯾد ﻟﯾﮭﺎ ‪NOTE//‬‬
‫اﻧﻣﺎ ﻟو اﻟﻣﯾﺛود ذات ﻧﻔﺳﮭﺎ اﺑﺳﺗراﻛت ﻻزم ﯾﺗﻌﻣل ﻧﻔس اﻟﻣﯾﺛوذ واﻻ ھﯾﺟﯾب اﯾرور‬
Final Var , Final Method
A final variable can be explicitly initialized only once.
A reference variable declared final can never be reassigned to
refer to a different object.
With variables, the final modifier often is used with static to
make the constant a class variable.

Final Variable… EX
: public class Test { final int value = 10;
public void changeValue() {
value = 12; // will give an error }

Final Method

A final method cannot be overridden by any subclasses.


The final modifier prevents a method from being
modified in a subclass.
EX:
Declaring a final method Example:
class X{ public final void sum(){} }
class Y extends X{
public void sum(){} // Error }

Final Class
final class is a class that cannot be extended by any
other class
EX : FROM GEEK
class Base {
final public void show() {
System.out.println("Base::show() called");
}
}

class Derived extends Base {


public void show() {
System.out.println("Derived::show() called");
}
}

class Main {
public static void main(String[] args) {
Base b = new Derived();;
b.show();
}
}

ANS // Error
Interface
An interface in Java is a blueprint of a class.
It has static constants and abstract methods.
There can be only abstract methods in the Java interface (no complete
methods inside!)
It is used to achieve abstraction and multiple inheritance in Java

Interface fields are public, static and final by default, and the
methods are public and abstract.
Example 1:
interface Drawable{ void draw(); }

class Rectangle implements Drawable{ public void


draw(){System.out.println("drawing rectangle");} }
// ‫اﺣﻧﺎ ﺑﻧﻌﻣل اﯾﻣﺑﻠﯾﻣﻧت ﻟﻠﻛﻼس ﻟو ﻋﻣل اﻛﺳﺗﻧد ﻏﻠط وھﯾﻌﻣل اﯾرور ﻋﺷﺎن ده‬
‫ﻓﺎﯾﻧﺎل ﻛﻼس ﻣﯾﻧﻔﻌش ﯾﻌﻣل اﻧﮭرت ﻣﻧﮫ‬
class Circle implements Drawable{ public void
draw(){System.out.println("drawing circle");} } //Using interface

class TestInterface1{ public static void main(String args[]){


Drawable d=new Circle(); }}
New Circle ‫ﺑﯾﺷﺎور ﻋﻠﻲ ﻛﻼس اﻟداﯾره ﻣش اﻻﻧﺗرﻓﯾس‬
PolyMorphism
Polymorphism is an OOP feature that allows programmers to
send the same message to objects from different classes.
‫ﻋﺑﺎره ان ﺑﻘدر اﻋﻣل اﻛﺳﯾس ﻋﻠﻲ اﻟﺳب ﻛﻼس ﺑﺎﺳﺗﺧدام اﻟﺳوﺑر ﻛﻼس‬
‫ﻣﺛﻼ‬
Class pet {}
Class cat extends pet {}
Class Dog extends pet {}
Pet p = new Dog();
Dog p = new pet(); // WRONG
‫ﻟو ﻓﯾﮫ ﻣﯾﺛود ﺧﺎﺻﮫ ﺑﺎﻟﺳب ﻛﻼس ﻓﻘط وﻣش ﻣوﺟوده ﻓﻲ اﻟﺳوﺑر ﻻزم اﻋﻣل‬
‫ﻛﺎﺳﺗﯾﻧﺞ‬
((dog)p).fetch()); // ‫ﻛﺎﺳﺗﯾﻧﺞ ﻋﺷﺎن اﻗدر أوﺻل ﻟﻠﻣﯾﺛود دي ﻋﺷﺎن ﻣش‬
‫ﻣوﺟوده ﻓﻲ اﻟﺳوﺑر ﻛﻼس‬
EX : FROM GEEK
class Base {
public static void show() {
System.out.println("Base::show() called"); }}
class Derived extends Base {
public static void show() {
System.out.println("Derived::show() called");}}
‫{ ‪class Main‬‬
‫{ )‪public static void main(String[] args‬‬
‫;)(‪Base b = new Derived‬‬
‫;)(‪b.show‬‬
‫}‬
‫}‬

‫‪ANS// Base::show() called‬‬


‫‪when a function is static, runtime polymorphism doesn’t happen.‬‬

‫‪INSTANCE OF OPERATOR‬‬
‫ﻟﮫ‬ ‫ﻟﻣﺎ ﺑﻌﻣل ﺳوﺑر ﻛﻼس وﯾﺑﻘﻲ ﻓﯾﮫ ﻛذا ﻛﻼس ﺑﯾﻌﻣﻠوا اﻧﮭﯾرت‬
‫واطﺑﻖ ﻓﻛره اﻟﺑوﻟﯾﻣورﻓﯾﻣز ﻋﻠﯾﮭم اﻧﻲ اﻋﻣل اري ﻟﯾﺳت ﻣن اﻟﺳوﺑر ﻛﻼس وادﺧل ﻓﯾﮭﺎ ﻛذا اوﺑﺟﻛت ﻣن‬
‫ﻛﻼﺳﯾز ﻣﺧﺗﻠﻔﮫ ﺑﺗﻌﻣل اﻧﮭرت ﻣﻧﮫ‬
‫ﻣﺛﻼ ﻟو داﯾره ﻓﻠﯾﮭﺎ ﻣﯾﺛود ﻣﻌﯾﻧﮫ ﻟطﺑﺎﻋﮫ اﻟﻣﺳﺎﺣﮫ وﻟو ﻣﺳﺗطﯾل وھﻛذا‬
‫ﻟﻣﺎ ﺑﺎﺟل اﻋﻣل ﻟوب ﻋﻠﻲ اﻻرﯾﻠﯾﺳت ﺑﺷوف ﻛل اوﺑﺟﯾﻛت ﺟواھﺎ ھو ﻣن اﻧﮭﻲ ﻛﻼس‬
‫‪if object from Arraylist instanceof circle‬‬
‫ﯾﺑﻘﻲ اطﺑﻊ اﻻوﺑﺟﯾﻛت ﺑﺗﺎع اﻟداﯾره‬
‫‪circle.getArea‬‬
‫ھﯾﺑﻘﻲ ده اوﺑﯾﺟﻛت ﻣن اﻟﻣﺳﺗطﯾل واطﺑﻊ ﻣﺳﺎﺣﮫ اﻟﻣﺳﺗطﯾل ‪else‬‬
Excep�on Handling

• An exception represents an error condition that can occur


during the normal course of program execution

• .It causes the program to terminate its normal flow.

• For example, if you access an array using an index that is


out of bounds, you will get a runtime error with an
ArrayIndexOutOfBounds Exception.

• If you enter a double value when your program expects an


integer, you will get a runtime error with an
InputMismatchException.

In Java, runtime errors are thrown as exceptions


An exception is an object that represents an error or a
condition that prevents execution from proceeding
normally.
If the exception is not handled, the program will terminate
abnormally.
When an exception occurs, we say an exception is thrown.
When the matching exception-handling code is executed, we
say the thrown exception is caught.
Some important Exception
ArithmeticExceptionIt is thrown when an exceptional
condition has occurred in an arithmetic operation.

♣ArrayIndexOutOfBoundsExceptionIt is thrown to indicate


that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size
of the array.

♣ClassNotFoundExceptionThis Exception is raised when


we try to access a class whose definition is not found

♣FileNotFoundExceptionThis Exception is raised when a


file is not accessible or does not open.CDS Programs,
ANU University25

IOExceptionIt is thrown when an input-output operation


failed or interruptedλ

InterruptedExceptionIt is thrown when a thread is waiting,


sleeping, or doing some processing, and it is interrupted

NoSuchFieldExceptionIt is thrown when a class does not


contain the field (or variable) specified
NoSuchMethodExceptionIt is thrown when accessing a
method which is not found.CDS Programs, ANU
University26

NullPointerExceptionThis exception is raised when


referring to the members of a null object. Null represents
nothing

NumberFormatExceptionThis exception is raised when a


method could not convert a string into a numeric format.

RuntimeExceptionThis represents any exception which


occurs during runtime.

λStringIndexOutOfBoundsExceptionIt is thrown by String


class methods to indicate that an index is either negative
or greater than the size of the string
Exception caught by Stack Trace

Ex :

IN stack Trace if we found exception we skip after parts


Ex :
In take input like age from user he could input nega�ve or string
YOU must make Try , Catch
Try {
Keep_Going=true;
While (Keep_Going){
Int age = sc.nextInt(); // if this input is right he will con�nue to next
Keep_Going = false; // break the loop
}catch (Excep�on e ){
System.out.printLn(“invaild”);
Sc.nextLine(); // this return to start from the beginning , remove le�over
garbage from the input buffer

}
}

// ‫ﻣﮭم ﺟداااااااااااااااااااااااااااااااااا‬
class Main {
public static void main(String[] args) {

System.out.println(1.0/0);
}]

ANS //
Infinity
This is because dividing a floating-point value by zero does not throw an exception in
Java, but instead produces a special value called Infinity. This value is defined in the
Double and Float classes as a constant.
You can make new excep�on if user put nega�ve
‫ﻟو دﺧل رﻗم ﺳﺎﻟب ﻣش ھﯾﺑﻘﻲ اﻛﺳﺑﺷن ﺑس اﻟﻌﻣر ﻣش ﺑﺎﻟﺳﺎﻟب‬
(:

Also You Can handle Mul� Excep�ons


try {
Scanner sc = new Scanner(System.in);
int x=sc.nextInt(); // exception
int a[] = new int[2];
int i = sc.nextInt(); //exception
a[i] = x; // exception
int z = x / 0; // exception

break;
} catch (InputMismatchException e) {
System.out.println(e);

} catch (ArrayIndexOutOfBoundsException s) {
System.out.println(s);

} catch (ArithmeticException v) {
System.out.println(v);

}
}
‫‪Note‬‬
‫اﻟﺑرﻧﺎﻣﺞ ھﯾﻘف ﻣﻊ اول اﻛﺳﺑﺷن ﻟو ﻣﻔﯾش ﻟوب وھﯾطﺑﻊ اﻷول ﺑس وﻣش ھﯾﻛﻣل‬

‫‪Finally Block‬‬

‫ﻣﮭم ﺟدا ان ﻟو ﻓﯾﮫ رﯾﺗرن ھﯾﻧﻔذ ﻓﺎﯾﻧﺎل ﻗﺑﻠﮭﺎ‬


‫اﻟﺣﺎﻟﮫ اﻟﻠﻲ ﻓﺎﯾﻧﺎل ﻣش ھﺗﺗﻧﻔذ ﻓﯾﮭﺎ ﻟو ﻓﯾﮫ‬
‫ﺑﺗﺧرج ﺑره اﻟﺑرﻧﺎﻣﺞ ﺧﺎﻟص ‪System.exit(0); //‬‬
Important Trace

Answers :
inside proc
AprocA'sfinally
Exception caught
inside procB
procB'sfinally
inside procC
procC'sfinally
try
{
int x = 0;
int y = 5 / x;
}
catch (Exception e)
{
System.out.println("Exception");
}
catch (ArithmeticException ae)
{
System.out.println(" Arithmetic Exception");
}
System.out.println("finished");

Compilation fails because ArithmeticException has already been


caught. ArithmeticException is a subclass of java.lang.Exception, by time
the ArithmeticException has been specified it has already been caught by
the Exception class.
If ArithmeticException appears before Exception, then the file will compile.
When catching exceptions the more specific exceptions must be listed before the more
general (the subclasses must be caught before the superclasses).
try
{
System.out.println("hello world ");
}
finally
{
System.out.println("Finally executing ");
}

Hello world Finally executing


Explanation:
Finally clauses are always executed. The program will first execute the try block,
printing Hello world, and will then execute the finally block, printing Finally executing.

Option A, B, and C are incorrect based on the program logic described above.
Remember that either a catch or a finally statement must follow a try. Since the finally is
present, the catch is not required.

System.out.print("Start ");
try
{
System.out.print("Hello world");
throw new FileNotFoundException();
}
System.out.print(" Catch Here "); /* Line 7 */
catch(EOFException e)
{
System.out.print("End of file exception");
}
catch(FileNotFoundException e)
{
System.out.print("File not found");
}

Line 7 will cause a compiler error. The only legal statements after try blocks are
either catch or finally statements.

Option B, C, and D are incorrect based on the program logic described above. If line 7
was removed, the code would compile and the correct answer would be Option B.

You might also like