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

CS202 – ADVANCED OO PROGRAMMING

CHAPTER 1
JAVA BASICS REVIEW
ABSTRACT CLASSES
INTERFACES
SOPHOMORE - SE
SPRING 2023
CS202 - ADVANCED OO PROGRAMMING 1
Outline
AGENDA

2
1. Visibility & Static Modifiers

2. Inheritance, Final, Abstract & Interfaces

3. Casting & Objects access

4. Overriding & Overloading

CS202 - ADVANCED OO PROGRAMMING


1. Access modifiers
▪ Public
▪ Default
▪ Protected
VISIBILITY ▪ private

2. Non-access modifier
▪ static

CS311
CS202
- ADVANCED
- ADVANCED
PROGRAMMING
OO 3
PROGRAMMING
Visibility Types (1)
There are two types of modifiers in Java: access modifiers and non-access
modifiers.

A Java access modifier specifies the accessibility or scope of a field, method,


constructor, or class.

We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.

Note: By default, an attribute or a method is not public : it is not accessible


from the other classes belonging to the same package.

Examples of non-access modifiers : final, abstract, static, transient, …

CS202 - ADVANCED OO PROGRAMMING 4


Visibility Types(2) – Access modifiers
➢ Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

➢ Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot
be accessed from outside the package.

➢ Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

➢ Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

CS202 - ADVANCED OO PROGRAMMING 5


Access modifier : Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Attribute Reading/writing or modification
Method Calling method
Class Instantiation objects of this class and access to its
attributes/methods

Example of public access modifier //save by B.java


package mypack;
import pack.*;
//save by A.java
package pack; class B {
public class A { public static void main(String args[]){
A obj = new A();
public void msg() obj.msg();
{ System.out.println("Hello"); } }
} }

CS202 - ADVANCED OO PROGRAMMING 6


Access modifier : Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only. The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class. It provides more accessibility than the default modifer.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

//save by B.java
package mypack;
//save by A.java import pack.*;
package pack; class B extends A {
public class A { public static void main(String args[]){
protected int att; B obj = new B();
protected void msg() obj.att = 2;
{ System.out.println("Hello");} obj.msg(); }
} }

CS202 - ADVANCED OO PROGRAMMING 7


Access modifier : Default
If no modifier is used, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by B.java
package mypack;
import pack.*;
class B {
public static void main(String args[])
//save by A.java { A obj = new A(); //Compile Time Error
package pack; obj.msg(); //Compile Time Error
class A { }
void msg() } /* The scope of class A and its method msg() is default so it
{ System.out.println("Hello");} cannot be accessed from outside the package.*/
}

CS202 - ADVANCED OO PROGRAMMING 8


Access modifier : Private
The private access modifier is accessible only within the class.

Example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a compile-
time error.
package pack;
class A {
private int data=40;
private void msg()
{ System.out.println("Hello java");}
}

public class Simple {


public static void main(String args[])
{
A obj = new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

CS202 - ADVANCED OO PROGRAMMING 9


Access modifiers

Public Protected default Private

Within class Yes Yes Yes Yes


Within package Yes Yes Yes No
Outside package by sub-class Yes Yes No No
Outside package Yes No No No

CS202 - ADVANCED OO PROGRAMMING 10


1
0
Static modifier
The methods and attributes decalred as static are relative to the class and not to a particular
instance/object.

attributes: the value of a static attribute is not realtive to the object but to the class (same
value of this attributes for all objects instantiating this class)

We can access directly by using the class name instead of using object name or by calling any object
instantiating this clase

Method: its code does not depend on an object et may be executed if there is no object
instantiating this class (example main)

Nested Classes

Every code used in/with static members can not reference the current instance or object (this)

CS202 - ADVANCED OO PROGRAMMING 11


Example
public class MyClass {
public static int counter = 0;
……..
}

public static void main(String [] args)


{
MyClass m = new MyClass ();
int c1 = m.counter;
int c2 = MyClass.counter;
//c1 et c2 have the same value
}

CS202 - ADVANCED OO PROGRAMMING 12


INHERITANCE 1. Inheritance
▪ Final
& ▪ Abstract
ABSTRACTION ▪ Interface

04/11/19 ADVANCED
CS202 - PROGRAMMING
ADVANCED OO 13
PROGRAMMING
Final modifier
The keyword final may be applied to :

➢ Class variables
➢ Instance variables
➢ Local variables
➢ Methods
➢ Method’s parameters
➢ Classes

We are not allowed to modify final entites

CS202 - ADVANCED OO PROGRAMMING 14


Final variables
A final variable is a variable which cannot be modified once initialized.
public class MyClass {
public final int const;

public MyClass () {

this.const = 10;} public class MyClass {


} //OK public static final int const = 0;

public MyClasse() {

this.const = 10;}

} //ERROR

Constants are qualified as final and static static.


public static final float pi = 3.14;

CS202 - ADVANCED OO PROGRAMMING 15


Final methods & classes

A final method cannot be redefined (overrided) in other sub-classes.

A final class

• Cannot be modified,
• Cannot be inherited (no sub-classes to be defined).

CS202 - ADVANCED OO PROGRAMMING 16


Abstract classes
In classical classes (normal), everything must be concrete
➢ All methods could be defined (signature and code)

➢ May have/include different visibility modifiers

An abstract class allows to create a halfway type


➢ It maycontain abstract methods
➢ It is considered as partially implemented, and thus non-instantiable
➢ It may eventually have no abstract method
➢ The keyword abstract makes it non-instantiable
➢ We force the inheritence

CS202 - ADVANCED OO PROGRAMMING 17


Abstract class : Example
public abstract class GeometricShape {
public double dim;
public GeometricShape (double x) {
this.dim = x; }
public void Display() {
System.out.println(“I am a geometric shape from unknown type”); }
public abstract double Surface(); //without implementation
}

public class Circle extends GeometricShape {


public Circle(double x) {
super(x); }
public void Display() {
System.out.println(“I am a circle of radius ” + super.dim); }
public double Surface() {
return (super.dim * 3.14); }
}

public class Rectangle extends GeometricShape {


public double dim2;
public Rectangle(double x, double y) {
super(x);
this.dim2 = y;}
public void Display () {
System.out.println(“I am a rectangle of dimensions ” + super.dim + “and” + dim2); }
public double Surface() {
return (super.dim * dim2); }}
CS202 - ADVANCED OO PROGRAMMING 18
Abstract class: Remarks
Generally:
➢ An abstract class may inherit from another abstract class;

➢ An abstract cass may inherit from a concrete class;

➢ A concrete classe inheriting from one or multiple abstract classes (indirectly), should implement all
the existing abstract methods

Abstract classes are highly used in standard API (Swing).

Using/defining an abstract class can be justified by:


➢ The current class will be inherited by many other classes;

➢ Abstract classes will be used throw commun methods having the same name.

For these two reasons, it is interesting tu define abstract classes.

CS202 - ADVANCED OO PROGRAMMING 19


Interfaces
Interfaces allow the implementation of the multiple inheritence
mechanism.

An interface is a set of constants and declaration of methods (looks a


little like abstract classes).

Like a class, an interface can have methods and variables, but the
methods declared in interface are by default abstract (only method
signature, no body).

▪▪ Interfaces specify what a class must do and not how. It is the blueprint of the class.

➔If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.

CS202 - ADVANCED OO PROGRAMMING 20


2
0
Why interfaces ?
▪▪ It is used to achieve total abstraction.

▪▪ Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .

▪▪ It is also used to achieve loose coupling.

▪▪ Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes? The reason is, abstract classes may
contain non-final variables, whereas variables in interface are final, public and
static.

CS202 - ADVANCED OO PROGRAMMING 21


Interfaces
Interfaces are declared using the keyword interface instead of class and
are integrated in other classes thanks to the keyword implements.
An interface is implicity declared as abstract ➔ the keyword abstract may
be omitted from the signatures of tmethods.
All the methods of interfaces should be public.
In interfaces, a private method is not useful as it cannot be implemented
later in other files

[public] interface myInterface {


// methods and/or static fields
}

CS202 - ADVANCED OO PROGRAMMING 22


Interfaces
An interface may inherit from one or multiple other interfaces. But it cannot inherit from a class
(conrete or abstract).

[public] interface myInterface [extends Interface1, Interface2 ... ] {


// methods and/or static fields
}
A class cannot inherit from an interface but it implements it thanks to the keyword implements.

➔ A class may implement multiple interfaces.

A concrete class should provide an implementation for all the methods declared in the
interfaces in question as well those are declared in super-classes (abstract).

Multiple interfaces may be implented in the same class.


class myClass [extends mySuperClass] [implements Interface1, Interface2, ...] {
…….
}

CS202 - ADVANCED OO PROGRAMMING 23


Example: description and implementation of an interface
public interface Screen {
public void display(String s);
public void warning();
}

class Phone implements Screen {


public void display(String s) {
System.out.println(s) ;}
void warning() {
display(”phone Warning !!”);}
void ring() {
System.out.println(”bip call !!”);}
}

class Computer implements Screen {


String Name;
public Computer(String n) {
this.name = n; }
public void display(String s) {
System.out.println(“computer name : “+ s); }
void warning () {
System.out.println(”Warning from computer : ” + name);
}

CS202 - ADVANCED OO PROGRAMMING 24


Example: Interfaces & references

/* Declaring a reference of the Screen interface */

Screen sc ; //error ➔➔cannot instantiate an interface


Screen sc = new Screen (); // not possible
sc.display(”my screen”); //????

// Instantiate a class implementing an interface :


Phone t = new Phone ();

// what about the following declarations?


Screen sc1 = t; // ????
Screen sc2 = new Computer(”My computer”); // ????
Screen sc3 = new Integer (2); // ????

CS202 - ADVANCED OO 25
PROGRAMMING
CASTING & ➢ Casting

OBJECTS ✓ Instanceof operator

ACCESS ➢ Object access


✓ This
✓ Super

04/11/19 CS311 - ADVANCED PROGRAMMING


Principle idea of the inheritence
The principal idea of the inheritence is to organize the classes in a hierarchical way. The
inheritence relations are unidirectional

If a class B inherits from a class A:

➔ B is a particular/specific case of A

➔ the objects instantiating the class B, are implicitely instantiating the class A

➔ The inheritence consists of defining a class, called sub-class, class child or derived class
from another one called mother class, super class or base class.

➔ the sub-class retreive automatically all members and behaviors from the the super-class and
may eventually define other specific ones.

CS202 - ADVANCED OO PROGRAMMING 27


Exemple
public class Pixel { Pixel

private int x; x:int

private int y; y:int

moveTo(int,int)
public void moveTo(int newX, int newY) {

this.x = newX;

this.y = newY;} ColoredPixel


} rgb:byte[]

public class ColoredPixel extends Pixel { getRed():byte

private byte[] rgb; getGreen():byte

getBlue():byte
public byte getRed() {return rgb[0];}
public byte getGreen() {return rgb[1];}
public byte getBlue() {return rgb[2];}
}

CS202 - ADVANCED OO PROGRAMMING 28


Objects instantiating derived classes
Each object instantiating a derived class is considered primarily as an object instantiating the
base class

➢➢first of all, a colored pixel is a pixel

Each object instantiating a derived class combines the derived attributes from the base class
with those defined in its own class

➢➢We have int x and int y in objects of the class ColoredPixel. We have also 3 colors (green, red, blue) for
each object of ColoredPixel
public static void main(String[] args) {
Pixel p = new Pixel();
p.moveTo(1, 1);

ColoredPixel cp = new ColoredPixel();


cp.moveTo(2, 2);

cp.getRed(); // NullPointerException
}

CS202 - ADVANCED OO PROGRAMMING 29


Constructors
The construction (and initialization) of all classes instances begins at first by constructing
(initializing) an object instance

➢➢Each constructor begins by calling the constructor of the super -class: super()

➢➢It should be the first instruction of the constructor

➢➢the default constructor (added by the compiler) call the default constructor of the super-class

public class Pixel {

public class ColoredPixel extends Pixel {


private int x;
private byte[] rgb;
private int y;

public ColoredPixel() {
public Pixel(int newX, int newY) {
this.x = newX; // not allowed
this.x = newX;
this.y = newY; // not allowed
this.y = newY; }
// super(); // Constructor Pixel() is undefined
// ...
} super(0,0); // OK; note that x and y are private!
rgb = new byte[3]; }
}

CS202 - ADVANCED OO 30
3
PROGRAMMING 0
Example
public class Employee{
protected String name ;
protected double salary ;
public Employee ( String n, double s){
this.name = n;
this.salary = s ;}
public String getName(){ return Name ;}
public double getSalary() { return salary ;}
public String toString() { return getName()+” ”+getSalary(); }
}

public class Manager extends Employe{


private double bonus;
public Manager ( String n, double s, double b){
super( n, s) ;
this.bonus = b;}
public double getSalary() {return salary + bonus;} //return super.getSalary() + bonus;
}

Employee enterprise[] = new Employee[5] ;


enterprise[0]= new Manager(”Jane", 1000, 500) ;
enterprise[1]= new Manager(”Marc", 1000, 600) ;
enterprise[2]= new Employe(”Julia", 620) ;
enterprise[3]= new Employe (”Karim", 700) ;
enterprise[4]= new Employe (“Leila", 100) ;

CS202 - ADVANCED OO PROGRAMMING 31


for ( int i = 0 ; i< 5 ; ++i){
if (entreprise[i] instanceof Manager)
System.out.print(”Manager : ");
System.out.println( enterprise[i].toString());
}

double sumSalaries = 0;
for ( int i = 0 ; i < 5 ; ++i)
if(!(enterprise[i] instanceof Manager))
sumSalaries += enterprise[i].getSalary();

CS202 - ADVANCED OO PROGRAMMING 32


Exercise
Description
-The class Student inherits from the class Person.
- The class Professor inherits from the class Employee (salary : double) which inherits from the class Person
-A Student (RegisID : String) is a Person having the following characateristics(ID, FirstName, LastName :
String).
- A Professor (speciality: String) is an Employee et un Employee is a Person.

Questions
- Write all the needed classes in Java.
- Each class should contain a constructor for initializing the objects to be created.
- Each class should redefine the method toString().
-Write a principal program in separate class to create two wtudents, two professors and two employees.
The program should display all the informations about the created objects.

CS202 - ADVANCED OO 33
PROGRAMMING
Class Person

public class Person {

protected int id;


protected String FName, LName ;
private static int count;

public Person (String LN, String FN) {


this.id = ++count;
this. FName = FN;
this. LName = LN;
System.out.println(“a new person is created”);
}

@Override
public String toString() {
return ”I am " + this.LName.toUpperCase() + " ”
+ this.FName.substring(0, 1).toUpperCase() + ””
+ this.FName.substring(1).toLowerCase();
}
}
CS202 - ADVANCED OO PROGRAMMING 34
Class Student

public class Student extends Person {

private String RegisID;

public Student(String LN, String FN, String id) {


super(LN, FN);
this.RegisID = id;
System.out.println(“a new student is created”);
}

@Override
public String toString() {
return super.toString() + " my registration number is : " + this. RegisID;
}

CS202 - ADVANCED OO PROGRAMMING 35


Class Employee

public class Employee extends Person {

protected double Salary;

public Employee(String LN, String FN, double S) {


super(LN, FN);
this.salary = s;
System.out.println(“a new employee is created”);
}

@Override
public String toString() {
return super.toString() + " my salary is: " + this.Salairy + " D";
}

CS202 - ADVANCED OO PROGRAMMING 36


Class Professor

public class Professor extends Employee {

private String Speciality;

public Professor(String LN, String FN, double S, String Sp) {


super(LN, FN, S);
this.Speciality = sp;
System.out.println(“a new professor is created”);
}

@Override
public String toString() {
return super.toString() + " my speciality is : " + this.speciality;
}

CS202 - ADVANCED OO PROGRAMMING 37


Principal program

public class Program {


public static void main(String[ ] main) {

Employee[ ] E = new Employee[2];


E[0] = new Employee(”Gharbi", "Rachid", 10000);
E [1] = new Employee(”Slama", ”Ahmed", 10000);
System.out.println(E[0]);
System.out.println(E[1]);

Student[] S = new Student[2];


S[0] = new Student(”Salhi", ”Ahmed", "65678754");
S[1] = new Student(”Abidi", ”Leila", "87543543");
System.out.println(S[0]);
System.out.println(S[1]);

Professor[] P = new Professor[2];


P[0] = new Professor("Fersi", "Maya", 5700, "JAVA/JEE");
P[1] = new Professor("Gharbi", "Ali", 5000, "Maths");
System.out.println(P[0]);
System.out.println(P[1]);
}
}

CS202 - ADVANCED OO PROGRAMMING 38


Hidden fields - comments
It is not possible to create an attribute in a child-class having the same
name as another belonging to the mother-class

➢➢ It is rarely useful, but generally a bad idea since it presents a source of error

Super ➔ this seen with the type of the super-class

➢ super.super.x does not exist neither ref.super.x

We can do only ref.super

➔ Solution : casting using (cast) allow to change or convert the type of the
decalred reference (or object)

CS202 - ADVANCED OO 39
PROGRAMMING
class A {
int x = 1; }

class B extends A {
String x = "zz"; }

class C extends B {
boolean x = true;

public static void main(String[] args) {


C c = new C();
System.out.println(c.x); // true
System.out.println(((B)c).x); // zz
System.out.println(((A)c).x); // 1
}
}

CS202 - ADVANCED OO 40
4
PROGRAMMING 0
Question
How can we modify the first or last name of a professor?
Instanceof operator
It is possible to perform the conversion/casting correctly without exceptions
thanks to the operator instanceof ➔ x instance of T

X should be a variable which references an object or null

T is a type (primitive, non-primitive, class, etc)

The result is true when x is not null and can be assigned to a variable of type T without
ClassCastException; otherwise, it is false.
class A { }
class B extends A { } A ab = null;
System.out.println(ab instanceof A); // false
class C extends B { }
ab = new B();
System.out.println(ab instanceof A); // true
System.out.println(ab instanceof B); // true
System.out.println(ab instanceof C); // false

CS202 - ADVANCED OO 42
PROGRAMMING
Overriding
POLYMORPHISM
Overloading

04/11/19 ADVANCED PROGRAMMING


Method overriding
Giving anoher implementation to the same method:

Same name, same parameters, different code


public class Pixel {
private int x;
private int y;

public Pixel(int newX, int newY) { public class ColoredPixel extends Pixel {
this.x = newX; private byte[] rgb;
this.y = newY; }

public void display() {


public void display() {
System.out.println(x); super.display();
System.out.println(y);}
} System.out.println("["+rgb[0]+":"+rgb[1]+":"+rgb[2]+"]”);
}
}

CS202 - ADVANCED OO 44
PROGRAMMING
Method overloading
If the method signature is different from the one defined in the super class, it is called
overloading :
Both methods have the same name but have different parameters Generally,
both are defined in the same child class

class Pixel {
void m1() { ... }
void m2() { ... }
Pixel m3() { ... }
void m4(Pixel p) { ... }
}
class ColoredPixel extends Pixel {
void m1() { ... } // overriding
void m2(int a) { ... } // overloading
ColoredPixel m3() { ... } // overriding
void m4(Pixel p) { ... } // overriding
void m4(ColoredPixel p) { ... } // overloading
}

CS202 - ADVANCED OO 45
PROGRAMMING
Example – classes definition
public class Employee{
protected String name ;
protected double salary ;
public Employee ( String n, double s){
this.nom = n ;
this.salary = s ;}
public String getName(){ return name ;}
public double getSalary() { return salary ;}
public String toString() { return getName()+” ”+getSalary(); }
}

public class Chief extends Employee{b){


protected double bonus ;
public Chief ( String n, double s){
super( n, s) ;
this.bonus = b;}
public double getSalary() {return salary + bonus;} //return super.getSalaire() + bonus;
}

CS202 - ADVANCED OO 46
PROGRAMMING
Example – principal program
Employee enterprise[] = new Employee[5] ;
enterprise[0]= new Chief("Cronos", 1000, 500) ;
enterprise[1]= new Chief("Zeus ", 1000, 600) ;
enterprise[2]= new Employee("Ares", 620) ;
enterprise[3]= new Employee ("Apollon", 700) ;
enterprise[4]= new Employee ("Aphrodite ", 100) ;

for ( int i = 0 ; i< 5 ; ++i){


if (enterprise[i] instanceof Chief)
System.out.print("Chief : ");
System.out.println( enterprise[i].toString());}

double sumSalaries = 0;
for ( int i = 0 ; I < 5 ; ++i)
if(!(enterprise[i] instanceof Chief))
sumSalaries += enterprise[i].getSalary();

CS202 - ADVANCED OO 47
PROGRAMMING

You might also like