SOFT2201/COMP9201
Software Construction and Design I
Week 2: OO Theory in Java
Dr. Ying Zhou, School of Computer Science
Table of
Contents
01 Java Data Types Review
02 Four pillars of OOP
03 Encapsulation in Java
04 Abstraction in Java
05 Inheritance in Java
06 Polymorphism in Java
2
Java Data Types Review
- Primitive type
- Non-Primitive Type
Java Data Types
• Java is a strongly typed language
• Primitive Data Types: build-in types of the virtual machine
• Cannot be changed by programs
• Have same meaning across computer platforms
• Non-primitive Data Types
• Predominantly user-defined, with some exceptions
4
The Eight Primitive Data Types
• Integral types
• byte, short, int, long
• Floating point number types
• float, double
• Character type
• char
• Boolean
• boolean
5
Storage Size, min and max values
6
Type Internal Smallest Value Largest Value
byte 8 bits -128 (-2^7) +127 (2^7 -1)
short 16 bits -32,768 +32,767
int 32 bits -2,147,483,648 +2,147,483,647
long 64 bits -2.3E+18 +2.3E+18
float 32 bits -/+1.4e-45 -/+3.4e+38
double 64 bits -/+4.9e-324 -/+1.7e+308d
Conversion between Primitive Types
• Implicit widening of integral & floating point number types
• byte to short, int, long, float, or double
• short to int, long, float, or double
• char to int, long, float, or double
• int to long, float, or double
• long to float or double
• float to double
• Everything else requires explicit type casts or is not possible
Casting/Widening Matrix
To byte
8 bits
char
16 bits
short
16 bits
int
32 bits
long
64 bits
float
32 bits
double
64 bits
Boolean
JVM
dependentFrom
byte n/a
char (byte) (short) n/a
short (byte) (char) n/a
int (byte) (char) (short) n/a
long (byte) (char) (short) (int) n/a
float (byte) (char) (short) (int) (long) n/a
double (byte) (char) (short) (int) (long) (float) n/a
boolean n/a n/a n/a n/a n/a n/a n/a
Example for Implicit Widening and Casting
…
byte x = 10;
/* implicit widening */
short y = x;
long z = x;
float f = x;
/* casting */
byte p = (byte) z;
short q = (short) f;
Casting a long value z to a byte type, the result may be unexpected
if the value hold by z is outside the byte range -128 ~ 127, but in this
case, the value is 10
Casting a float value f to a byte short, there could be data loss or the
result may be unexpected if the value hold by f is outside the short
range -32,768 ~ 32,767
Overflow and Underflow
• Adding a positive value to the maximum value a variable can hold or
subtracting a positive value from the minimum value a variable can hold will
result in overflow and under flow
• In Java, this usually just wraps the number around
int maxValue = Integer.MAX_VALUE;
int minValue = Integer.MIN_VALUE;
System.out.println(maxValue); // print out 2147483647
System.out.println(minValue); // print out -2147483648
int overflow = maxValue + 1;
System.out.println(overflow); // print out -2147483648
Non-primitive Types - Class
• Java Classes are types
• We can declare a variable whose type is a class
11
class Demo {
int a, b;
// Constructor
Demo(int a, int b) {
this.a = a; this.b = b;
}
// Method to add two numbers
int addition() { return a + b; }
// Method to subtract two numbers
int subtraction() { return a - b; }
}
public class Main {
public static void main(String[] args) {
Demo d1 = new Demo(10,4);
System.out.println(d1.addition());
System.out.println(d1.subtraction());
}
}
The variable d1 is of Demo type and hold
a reference to an object created using
the constructor of class Demo.
Basic Java Classes
• A basic class has name, fields and
methods
• A class is defined using the keyword
class followed by its name
• The Demo class has two fields (instance
variables): a and b
• and two methods and a special method
called Constructor
• Inside the constructor,the this keyword
is used to refer to the current object.
• It allows us to differentiate the instance
variable a, b and the parameter a and b.
12
class Demo {
int a, b;
// Constructor
Demo(int a, int b) {
this.a = a;
this.b = b;
}
// Method to add two numbers
int addition() { return a + b; }
// Method to subtract two numbers
int subtraction() { return a - b; }
}
Basic Java Object
• A class is a blueprint or a template
• An object is a specific instance of a class.
• Each object has a unique identity but shares the structure provided by its
class.
• Objects are created using the new keywords
13
public class Main {
public static void main(String[] args) {
Demo d1 = new Demo(10,4);
System.out.println(d1.addition());
System.out.println(d1.subtraction());
}
}
Each object gets a copy of the
instance variables.
The object referenced by d1 has its
own integer variables a and b
This is contrast to static variables,
which belongs to the class and there
is only one copy
Non-primitive Type - String
• String is a fundamental component in any language, in Java, it is defined by
the String class
• Example Strings
14
String s1 = "Scaler";
String s2 = new String("Academy");
Non-primitive Type - Array
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• Declared using square brackets
• Example arrays
15
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
Non-primitive Type - Interface
• Interface is a Java construct
used to group related
methods with empty bodies
• It acts like a contract. Classes
that decide to "sign" this
contract are required to
provide implementations for
all its methods.
• This is done through
“implements” the interface.
16
// Interface
interface Animal {
public void animalSound(); // interface method
public void sleep(); // interface method}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
Primitive vs. Non-primitive data types
• Origin
• Primitive types are innately defined in Java.
• Non-primitive types are predominantly user-defined, with some exceptions like String,
Array and others
• Value Storage
• Primitive data types are designed to hold a single value.
• Non-primitive types can encompass multiple values or even complex behaviors
• Memory Allocation
• Primitive types are allocated memory on the stack
• Non-primitive types, the stack merely contains a reference, while the actual object
resides in the heap memory
17
Four Pillars of OOP
Java Object Oriented Programming
• Object-oriented programming (OOP) is a programming paradigm based on the
concept of objects, which can contain data and code
(https://en.wikipedia.org/wiki/Object-oriented_programming).
• Classes and Objects are the two main aspects of Java OOP
• Class is a blueprint or a template for an object
• An object is an instance of a class
• Both class and object can have data and code part
• Data and code belong to a class should be declared using a static keyword
• The data part belong to an object is referred to as fields or instance variables;
• The code part is referred to as methods.
19
Four pillars/principles of OOP
• Encapsulation: Bundles the data and operations on that data into a single unit.
Hiding the internal state and some functionality of an object from the outside
world.
• Inheritance: Allows one class to inherits data and methods from another. Enabling
the reuse of code and the establishment of hierarchical relationships.
• Abstraction: Hide complex implementation details and only show essential
features, reducing complexity and enhancing understanding.
• Polymorphism: Allows objects to take on different forms or have multiple
behaviors, enabling flexibility and versatility in programming.
20
Encapsulation in Java
Key Elements
• In Java, encapsulation is about data protection and controlled access.
• Key elements of encapsulation in Java:
• Private Access Modifier
• The class fields should be declared as private
• They are only accessible within that class
• Public Access Modifier
• Some methods can be declared as public
• These methods can be accessed from anywhere in the program.
• Getter and Setter methods
• Provide public methods to access and modify private fields
• Allow controlled access to data while maintaining encapsulation
22
Encapsulation Example
• The field name has a private access
modifier
• The getName method returns the
value of the variable name.
• The setName method takes a
parameter (newName) and assigns it
to the name variable.
• Both getter and setter are declared
as public
• The this keyword is used to refer to
the current object.
23
public class Person {
// private = restricted access
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Encapsulation Example (cont’d)
24
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John”
System.out.println(myObj.getName());
}
}
An object of the Person class is created
using a system provided default constructor,
the field value is not specified
The print method uses the
getter method to obtain the
field value
The field value is
assigned using
the setter
method
public class Person {
// private = restricted access
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Benefits of encapsulation
• Control: Using encapsulation, we can add conditions to control how data is
accessed or modified.
• Flexibility and Maintenance: By encapsulating data, any internal changes to
a class won't directly affect its interactions with other classes.
• Increased Security: Shielding class members and only allowing them to be
changed through controlled methods ensures security.
• Modular Approach: Encapsulation allows a system to be split into clear, well-
defined modules, which can then be developed and maintained separately.
25
Inheritance in Java
Key element and features
• Inheritance allows programmers to create new classes (subclasses) by
inheriting properties and methods from existing classes (superclasses). This
promotes code reusability and hierarchical relationships between classes.
• Java supports inheritance through the extends keyword.
• subclass extends superclass
• Java supports single inheritance, meaning a class can extend only one
superclass.
• Multiple subclasses can inherit from a single superclass.
• Subclass inherits all accessible fields and methods from its superclass.
27
Inheritance of data members
• A subclass inherits all non-private data members from its superclass.
• Any field declared as public, protected, or with default access (package-private) in the
superclass becomes available to the subclass.
• Data members declared as private in the superclass are not accessible to the subclass.
28
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
The subclass Car has access to two fields: brand as part of the
superclass and modelName as its own private field
Inheritance of methods
• A subclass inherits all non-private methods from its superclass.
• A subclass can override a method inherited from the superclass by
providing a new implementation with the same signature (name, parameter
types, and return type).
• Method Overloading vs. Method Overriding
• Method overloading lets a class have several methods with the same name but different
parameters, allowing varied actions based on parameters.
• Method overloading is not related to inheritance but to methods within a
class.
29
Method Inheritance Example
30
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
class ScientificCalculator extends Calculator {
@Override
int add(int a, int b) {
// Just for illustration: adding 10 to the result
return a + b + 10;
}
}
public class OverloadOverrideExample {
public static void main(String[] args) {
ScientificCalculator myCalc = new ScientificCalculator();
// This will print 18
System.out.println(myCalc.add(5, 3));
// This will print 10
System.out.println(myCalc.add(5, 3, 2));
}
} In the Calculator class, the method add
is overloaded. It has two implementations
with different paramters
The ScientificCalculator class
inherited both methods from the
Calculator class. It provides a
different implementation to the
version with two parameters, this is
called overriding.
Constructor Inheritance
• Constructors are not inherited
• If a superclass has multiple constructors with different parameters, the subclass does
not get them through inheritance
• A subclass needs to provide its own constructors if the default one is not enough
• Implicit call to superclass constructor: When a subclass constructor is
invoked, the first statement is a call to the superclass’s default constructor.
• Explicit call to superclass constructor: we can explicitly call a specific
superclass constructor using the super keyword followed by the desired
arguments.
31
Chain of constructor calls example
32
class Grandparent {
Grandparent() {
System.out.println("Grandparent's constructor called.");
}
}
class Parent extends Grandparent {
Parent() {
System.out.println("Parent's constructor called.");
}
}
class Child extends Parent {
Child() {
System.out.println("Child's constructor called.");
}
}
Chain of constructor calls example
33
public class ConstructorChainExample {
public static void main(String[] args) {
new Child();
}
}
Grandparent's constructor called.
Parent's constructor called.
Child's constructor called.
Abstraction in Java
Java Mechanism
• Abstraction is the process of hiding certain details and showing only
essential information
• Abstraction can be achieved with either abstract classes or interfaces in
Java
35
Abstract Classes
• Abstract class is defined using the abstract keyword
• A class without an abstract keyword is a concrete class
• The abstract keyword can be used for methods as well
• An abstract method does not have a body;
• It can only be used in an abstract class
• An abstract class can contain both abstract methods and regular methods
• It serves as a blueprint for other classes
• Abstract classes cannot be instantiated directly
36
Abstract class example
37
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Pig extends Animal {
public void animalSound() { // The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
An abstract method
An regular method
Interface
• Java has no multi-inheritance
• Interface is a way-out (introduction of multi-inheritance via the back-door)
• An interface is completely "abstract" that is used to group related
methods with empty bodies.
• Interfaces can inherit from other interfaces
• It is declared using the keyword Interface followed by a name
38
Interface example – basic syntax
39
// Declare an interface named Printable
interface Printable {
void print(); // An abstract method with no implementation
}
// Declare an interface named Constants
interface Constants {
// Declare constant variables (implicitly public, static, and final)
int MAX_VALUE = 100;
String APP_NAME = "MyApp";
}
Interface example – inheritance
40
// Declare an interface named Drawable
interface Drawable {
void draw();
}
// Another interface that extends Drawable
interface Resizable extends Drawable {
void resize();
}
Interface Resizable has two methods: draw() and resize()
Interface Example- Implementation
41
interface Shape {
void draw(); // Abstract method
}
// Create a class Circle that implements the Shape interface
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a Circle");
}
}
Interface Example – multiple interface implementation
42
// Declare two interfaces
interface Printable {
void print();
}
interface Displayable {
void display();
}
// A class that implements both Printable and Displayable interfaces
class Document implements Printable, Displayable {
public void print() {
System.out.println("Printing document...");
}
public void display() {
System.out.println("Displaying document...");
}
}
Polymorphism in Java
Polymorphism
• Means many forms, it occurs when we have many classes that are related
to each other by inheritance or implementation
• A method can behave differently depending on the objects it is called on or
depending on the parameters passed to it
• Polymorphism in Java is mainly achieved through overloading or overriding
• Compile-time Polymorphism (Static Polymorphism)
• Run-time Polymorphism (Dynamic Polymorphism)
44
Static polymorphism example
45
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
class Main {
public static void main(String[] args) {
Calculator cal = new Calculator();
System.out.println(cal.add(1,3));
System.out.println(cal.add(1.5,3.5));
}
}
Dynamic polymorphism example
46
public class Shape{ // superclass
double area() { }
}
public class Rectangle extends Shape {// subclass
double area() { }
}
…
Shape X = new Shape();
Shape Y = new Rectangle();
double a1 = X.area() // invokes area of Shape
double a2 = Y.area() // invokes area of Rectangle
Both variables x and
y have the same
type Shape
But they reference
different objects of
different types
At runtime, Java uses the
object's actual class (like
Shape, or Rectangle) to
determine which version
of an overridden method
should execute.
Casting in Polymporphism
• Upcasting: This involves casting an object to one of its superclass types.
Being an implicit conversion, it's safe and is done implicitly, similar to
widening in primitive types
Shape Y = new Rectangle();
• Downcasting: We cast an object to one of its subclass types. It must be done
explicitly due to potential risks.
Shape Y = new Rectangle();
Rectangle Z = (Rectangle) Y
47
Reference
• Vahe Ashlanyan, Learn Java Fundamentals – Object-Oriented Programming
[Full Book]
• Freecodecamp: https://www.freecodecamp.org/news/learn-java-object-oriented-
programming/
• Chapter 2, 4
• W3C schools Java Tutorial
• https://www.w3schools.com/java/default.asp