CSEN401 - Lecture 2
CSEN401 - Lecture 2
Lecture 2 - Inheritance+Encapsulation
[email protected]
[email protected]
[email protected]
18.2.2024 − 22.2.2024
© Slim Abdennadher L2- Inheritance+Encapsulation 1/23
Inheritance Encapsulation Recap
Outline
1 Inheritance
2 Encapsulation
3 Recap
Inheritance: Intuition
Inheritance
A way to describe family of types when one subclass (child)
“inherits” instance variables and instance methods from a
superclass (parent).
Inheritance in Java
• To define a class B to be a subclass of a class A:
class B extends A {
.... }
• Several classes can be declared as subclasses of the same
superclass.
• Inheritance can also extend over several generations of classes.
Superclass: Person
public class Person {
String name;
public Person() {
name = "No name yet";
}
public Person(String initialName) {
name = initialName;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
© Slim Abdennadher L2- Inheritance+Encapsulation 7/23
Inheritance Encapsulation Recap
Outline
1 Inheritance
2 Encapsulation
3 Recap
Encapsulation
Encapsulation
Example
class CheckingAccount {
private String accountNumber;
private String accountHolder;
private int balance;
int currentBalance()
{
return balance ;
}
void processDeposit( int amount )
{
balance = balance + amount ;
}
....
}
Private Metods
• A private method of an object can be used only by the other
methods of the object.
• Parts of a program outside of the object cannot directly use a
private method of the object.
• Example:
class CheckingAccount
{ private int balance;
private int useCount = 0;
private void incrementUse()
{ useCount = useCount + 1; }
void processDeposit( int amount )
{ incrementUse();
balance = balance + amount ;
}
}
© Slim Abdennadher L2- Inheritance+Encapsulation 16/23
Inheritance Encapsulation Recap
Thedefault Visibility
Outline
1 Inheritance
2 Encapsulation
3 Recap
• OOP features.
• Objects and Classes.
• Instance Variables and Constructors.
• Instance and Class Methods.
• Class Variables.
• Uses of the this keyword.