You are on page 1of 42

COM323 Programming in Java

Week 02 – Data Types

© 2021. Cavendish University. Private and Confidential


Agenda

Learning outcomes of this module are to:

1. Primitive and reference types


2. Variables
3. Objected-Oriented programming in Java
4. Array declaration construction and initialization
5. Arrays as first-class objects

07-Mar-22 © 2021. Cavendish University. Rights Reserved 1


1. Primitive and reference types – Example 1

public class ComputeArea {


public static void main(String[] args) {
double radius; // Declare radius
double area; // Declare area

// Assign a radius
radius = 20; // radius is now 20
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
07-Mar-22 © 2021. Cavendish University. Rights Reserved 2
1. Primitive and reference types – Example 2

import java.util.Scanner; // Scanner is in the java.util package


public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter a radius
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();
// Compute area
double area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
07-Mar-22 © 2021. Cavendish University. Rights Reserved 3
1. Primitive and reference types – Example 3

import java.util.Scanner; // Scanner is in the java.util package


public class ComputeAverage {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter three numbers
System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();
// Compute average
double average = (number1 + number2 + number3) / 3;
// Display results
System.out.println("The average of " + number1 + " " + number2 + " "
+ number3 + " is " + average);
}
}
07-Mar-22 © 2021. Cavendish University. Rights Reserved 4
1. Primitive and reference types – Example 4a

public class Account {


private String name; // instance variable
// method to set the name in the object

public void setName(String name) {


this.name = name; // store the name
}

// method to retrieve the name from the object


public String getName() {
return name; // return value of name to caller
}
}

07-Mar-22 © 2021. Cavendish University. Rights Reserved 5


1. Primitive and reference types – Example 4b

import java.util.Scanner;
public class AccountTest {
public static void main(String[] args) {
// create a Scanner object to obtain input from the command window
Scanner input = new Scanner(System.in);

// create an Account object and assign it to myAccount


Account myAccount = new Account();

// display initial value of name (null)


System.out.printf("Initial name is: %s%n%n", myAccount.getName());

// prompt for and read name


System.out.println("Please enter the name:");
String theName = input.nextLine(); // read a line of text
myAccount.setName(theName); // put theName in myAccount
System.out.println(); // outputs a blank line

// display the name stored in object myAccount


System.out.printf("Name in object myAccount is:%n%s%n", myAccount.getName());
}
}

07-Mar-22 © 2021. Cavendish University. Rights Reserved 6


1. Primitive and reference types

Java’s types are divided into primitive types and reference types.
Primitive type:
• Ex: int, boolean, byte, char, short, long, float and double
• Variable can hold exactly one value of its declared type at a time.
• instance variables are initialized by default
• Can be initialized by assigning the variable a value in its declaration
Nonprimitive types or reference types:
• Classes, which specify the types of objects.
• Are used to store the locations of objects.
• May each contain many instance variables.
• If not explicitly initialized, are initialized by default to the value null—
which represents a “reference to nothing.”
• Are accessed through methods on an object, you need a reference to the
object

07-Mar-22 © 2021. Cavendish University. Rights Reserved 7


1. Primitive and reference types

Source: Liang (2012)

07-Mar-22 © 2021. Cavendish University. Rights Reserved 8


1. Primitive and reference types

Source: Liang (2012)

07-Mar-22 © 2021. Cavendish University. Rights Reserved 9


2. Variables

Source: Liang (2016)


07-Mar-22 © 2021. Cavendish University. Rights Reserved 10
2. Variables

import java.util.Scanner;

public class DisplayTime {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: ");
int seconds = input.nextInt();

int minutes = seconds / 60; // Find minutes in seconds


int remainingSeconds = seconds % 60 ; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes +
" minutes and " + remainingSeconds + " seconds");
}
}
07-Mar-22 © 2021. Cavendish University. Rights Reserved 11
2. Variables

07-Mar-22 © 2021. Cavendish University. Rights Reserved 12


3. Object Oriented Programming

What are OOP concepts in Java?


OOP concepts allow us to create specific interactions
between Java objects. They make it possible to reuse code
without creating security risks or making a Java program
less readable.

• Abstraction
• Polymorphism
• Inheritance
• Encapsulation

07-Mar-22 © 2021. Cavendish University. Rights Reserved 13


3. Object Oriented Programming

Object oriented Programming in 7 Minutes

https://www.youtube.com/watch?v=pTB0EiLXUC8

Fundamental Concepts of Object-Oriented Programming

https://www.youtube.com/watch?v=m_MQYyJpIjg&list=RDLVpTB0EiLXUC8&index=4

07-Mar-22 © 2021. Cavendish University. Rights Reserved 14


3. Object Oriented Programming

Java is a class-based object-oriented programming (OOP) language


that is built around the concept of objects. OOP concepts (OOP)
intend to improve code readability and reusability by defining how
to structure a Java program efficiently.

• Abstraction A
• Polymorphism
• Inheritance
• Encapsulation

Using OOP Concepts to write high-performance Java code

07-Mar-22 © 2021. Cavendish University. Rights Reserved 15


3. Object Oriented Programming

Abstraction

Abstraction aims to hide complexity from the users and show them only the relevant
information. For example, if you want to drive a car, you don’t need to know about its
internal workings. The same is true of Java classes. You can hide internal
implementation details by using abstract classes or interfaces. On the abstract level,
you only need to define the method signatures (name and parameter list) and let
each class implement them in their own way.

Abstraction in Java:
▪ Hides the underlying complexity of data
▪ Helps avoid repetitive code
▪ Presents only the signature of internal functionality
▪ Gives flexibility to programmers to change the implementation of the abstract
behaviour
▪ Partial abstraction (0-100%) can be achieved with abstract classes
▪ Total abstraction (100%) can be achieved with interfaces

07-Mar-22 © 2021. Cavendish University. Rights Reserved 16


3. Object Oriented Programming

Encapsulation

Encapsulation allows us to protect the data stored in a class from system-wide


access. As its name suggests, it safeguards the internal contents of a class like a
real-life capsule. You can implement encapsulation in Java by keeping the fields
(class variables) private and providing public getter and setter methods to each of
them. Java Beans are examples of fully encapsulated classes.

Encapsulation in Java:

• Restricts direct access to data members (fields) of a class.

• Fields are set to private

• Each field has a getter and setter method

• Getter methods return the field

• Setter methods let us change the value of the field

07-Mar-22 © 2021. Cavendish University. Rights Reserved 17


3. Object Oriented Programming

Polymorphism

Polymorphism refers to the ability to perform a certain action in different ways. In


Java, polymorphism can take two forms: method overloading and method overriding.
Method overloading happens when various methods with the same name are
present in a class. When they are called they are differentiated by the number, order,
and types of their parameters. Method overriding occurs when the child class
overrides a method of its parent.

Polymorphism in Java:

▪ The same method name is used several times.

▪ Different methods of the same name can be called from the object.

▪ All Java objects can be considered polymorphic (at the minimum, they are of their
own type and instances of the Object class).

▪ Example of static polymorphism in Java is method overloading.

▪ Example of dynamic polymorphism in Java is method overriding.

07-Mar-22 © 2021. Cavendish University. Rights Reserved 18


3. Object Oriented Programming

Inheritance

Inheritance makes it possible to create a child class that inherits the fields and
methods of the parent class. The child class can override the values and methods of
the parent class, however it’s not necessary. It can also add new data and
functionality to its parent. Parent classes are also called superclasses or base
classes, while child classes are known as subclasses or derived classes as well.
Java uses the extends keyword to implement the principle of inheritance in code.

Inheritance in Java:
▪ A class (child class) can extend another class (parent class) by inheriting its
features.
▪ Implements the DRY (Don’t Repeat Yourself) programming principle.
▪ Improves code reusability.
▪ Multilevel inheritance is allowed in Java (a child class can have its own child
class as well).
▪ Multiple inheritances are not allowed in Java (a class can’t extend more than one
class).
07-Mar-22 © 2021. Cavendish University. Rights Reserved 19
3. Object Oriented Programming | Abstraction

An abstract class is a superclass (parent class) that cannot be instantiated. You


need to instantiate one of its child classes if you want to create a new object.

Abstract classes can have both abstract and concrete methods.

Abstract methods contain only the method signature, while concrete methods
declare a method body as well. Abstract classes are defined with
the abstract keyword. Example

Abstract class Animal


extends
interface
Bird Eagle

implement

“Instantiate” myBird myEagle

07-Mar-22 © 2021. Cavendish University. Rights Reserved 20


3. Object Oriented Programming | Abstraction

In the example below, you can see an abstract class called Animal with two
abstract and one concrete method.

abstract class Animal {


// abstract methods
abstract void move();
abstract void eat();

// concrete method void label() {


System.out.println("Animal's data:");
}
}
Animal.java

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 21


3. Object Oriented Programming | Abstraction

Extend the Animal abstract class with two child classes: Bird and Fish. Both of
them set up their own functionality for the move() and eat() abstract methods.
class Bird extends Animal {
void move() {
System.out.println("Moves by flying.");
}
void eat() {
System.out.println("Eats birdfood."); Bird.java
}
}

class Fish extends Animal {


void move() {
System.out.println("Moves by swimming."); Fish.java
}
void eat() {
System.out.println("Eats seafood.");
}
} Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 22


3. Object Oriented Programming | Abstraction

Now, test it with the TestBird and TestFish classes. Both call the one
concrete (label()) and the two abstract (move() and eat()) methods.

class TestBird { class TestFish {


public static void main(String[] args) { public static void main(String[] args) {
Animal myBird = new Bird(); Animal myFish = new Fish();

myBird.label(); myFish.label();
myBird.move(); myFish.move();
myBird.eat(); myFish.eat();
} }
} }

TestFish.java
TestBird.java

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 23


3. Object Oriented Programming | Abstraction

An interface is a 100% abstract class. It can have only static, final, and public fields and
abstract methods. It’s frequently referred to as a blueprint of a class as well. Java interfaces
allow us to implement multiple inheritance in our code, as a class can implement any
number of interfaces. Classes can access an interface using the implements keyword.

interface Animal {
public void eat();
public void sound();
}

interface Bird {
int numberOfLegs = 2;
String outerCovering = "feather";
Interfaces.java
public void fly();
}

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 24


3. Object Oriented Programming | Abstraction

The class Eagle implements both interfaces. It defines its own functionality for the three
abstract methods. The eat() and sound() methods come from the Animal class,
while fly() comes from Bird.

class Eagle implements Animal, Bird {


public void eat() {
System.out.println("Eats reptiles and amphibians.");
}
public void sound() {
System.out.println("Has a high-pitched whistling sound.");
}
public void fly() {
System.out.println("Flies up to 10,000 feet.");
}
} Eagle.java

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 25


3. Object Oriented Programming | Abstraction

In the TestEagle test class, instantiate a new Eagle object (called myEagle) and print
out all the fields and methods to the console.

As static fields don’t belong to a specific object but to a whole class, you need to
access them from the Bird interface instead of the myEagle object.

class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle(); TestEagle.java

myEagle.eat();
myEagle.sound();
myEagle.fly();

System.out.println("Number of legs: " + Bird.numberOfLegs);


System.out.println("Outer covering: " + Bird.outerCovering);
}
} Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 26


3. Object Oriented Programming | Encapsulation

With encapsulation, you can protect the fields of a class. To do so, declare the fields as private
and providing access to them with getter and setter methods.

The Animal class below is fully encapsulated. It has three private fields and each of them has its
own set of getter and setter methods.
class Animal2 {
// Setter methods
private String name;
public void setName(String name) {
private double averageWeight;
private int numberOfLegs; this.name = name;
}
// Getter methods public void setAverageWeight(double
public String getName() { averageWeight) {
this.averageWeight = averageWeight;
return name;
}
}
public void setNumberOfLegs(int
public double getAverageWeight() {
return averageWeight; numberOfLegs) {
} this.numberOfLegs = numberOfLegs;
public int getNumberOfLegs() { }
}
return numberOfLegs;
} Animal2.java
Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 27


3. Object Oriented Programming | Encapsulation

The TestAnimal class first sets a value for each field with the setter methods, then
prints out the values using the getter methods.

public class TestAnimal2 {


public static void main(String[] args) {
Animal2 myAnimal = new Animal2();

myAnimal.setName("Eagle");
myAnimal.setAverageWeight(1.5);
myAnimal.setNumberOfLegs(2);

System.out.println("Name: " + myAnimal.getName());


System.out.println("Average weight: " + myAnimal.getAverageWeight() + "kg");
System.out.println("Number of legs: " + myAnimal.getNumberOfLegs());
}
}

TestAnimal2.java
Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 28


3. Object Oriented Programming | Encapsulation vs Abstraction

ENCAPSULATION ABSTRACTION

Bird Animal

myAnimal
Animal2

Animal2 myAnimal = new Animal2(); Bird extends Animal


myAnimal.setName("Eagle"); Animal myBird = new Bird();
myAnimal.setAverageWeight(1.5); myBird.label();
myAnimal.setNumberOfLegs(2); myBird.move();
myBird.eat();

Tech Tutorials: Difference between Encapsulation and Abstraction in Java

07-Mar-22 © 2021. Cavendish University. Rights Reserved 29


3. Object Oriented Programming | Inheritance

Inheritance allows us to extend a class with child classes that inherit the fields and methods of the
parent class. It’s an excellent way to achieve code reusability. In Java, we need to use
the extends keyword to create a child class.

Base class Example

Bird3

extends
extends
Eagle3

“Instantiate”

myEagle

Derived class

Section 5.5 Inheritance, Polymorphism and Abstract Classes

07-Mar-22 © 2021. Cavendish University. Rights Reserved 30


3. Object Oriented Programming | Inheritance

In the example, the Eagle class extends the Bird parent class. It inherits all of its fields and
methods, plus defines two extra fields that belong only to Eagle.

class Bird3 {
public String reproduction = "egg";
public String outerCovering = "feather";

public void flyUp() {


System.out.println("Flying up...");
}
public void flyDown() {
System.out.println("Flying down...");
}
}
Bird3.java
class Eagle3 extends Bird3 {
public String name = "eagle";
public int lifespan = 15;
} Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 31


3. Object Oriented Programming | Inheritance

The TestEagle3 class instantiates a new Eagle object and prints out all the information (both the
inherited fields and methods and the two extra fields defined in the Eagle class).

class TestEagle3 {
public static void main(String[] args) {
Eagle3 myEagle = new Eagle3();

System.out.println("Name: " + myEagle.name);


System.out.println("Reproduction: " + myEagle.reproduction);
System.out.println("Outer covering: " + myEagle.outerCovering);
System.out.println("Lifespan: " + myEagle.lifespan);
myEagle.flyUp();
myEagle.flyDown(); TestEagle3.java
}
}

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 32


3. Object Oriented Programming | Polymorphism

Polymorphism makes it possible to use the same entity in different forms. In Java,
this means that you can declare several methods with the same name until they are
different in certain characteristics. Java provides us with two ways to implement
polymorphism: method overloading and method overriding.

Rectangles, ovals and roundrects are just morphed versions of a shape.

07-Mar-22 © 2021. Cavendish University. Rights Reserved 33


3. Object Oriented Programming | Polymorphism

Static polymorphism
Method overloading means that you can have several methods with the same name
within a class. However, the number, names, or types of their parameters need to be
different.

For example, the Bird4() class below has three fly() methods. The first one doesn’t
have any parameters, the second one has one parameter (height), and the third one
has two parameters (name and height).

overload overload

override
Bird Eagle at 10,000 ft
Bird at 10,000 ft

07-Mar-22 © 2021. Cavendish University. Rights Reserved 34


3. Object Oriented Programming | Polymorphism

The test class instantiates a new Bird object and calls the fly() method three times.
Firstly, without parameters, secondly, with one integer parameter for height, and
thirdly, with two parameters for name and height.

class TestBird4 {
public static void main(String[] args) {
Bird4 myBird = new Bird4();

myBird.fly();
myBird.fly(10000);
myBird.fly("eagle", 10000);
}
}
TestBird4.java

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 35


3. Object Oriented Programming | Polymorphism

By using the method overriding feature of Java, you can override the methods of a
parent class from its child class.

The Bird5 class extends the Animal class in the example below. Both have
an eat() method. By default, Bird5 inherits its parent’s eat() method. However, as it
also defines its own eat() method, Java will override the original method and
call eat() from the child class.

class Animal5 {
public void eat() {
System.out.println("This animal eats insects.");
}
} Animal5.java
class Bird5 extends Animal5 {
public void eat() {
System.out.println("This bird eats seeds.");
}

} Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 36


3. Object Oriented Programming | Polymorphism

The TestBird5 class first instantiates a new Animal object and calls its eat() method.
Then, it also creates a Bird object and calls the polymorphic eat() method again.

class TestBird5 {
public static void main(String[] args) {
Animal5 myAnimal = new Animal5();
myAnimal.eat();

Bird5 myBird = new Bird5();


myBird.eat();
}
} TestBird5.java

Adapted from: 6 OOP concepts in Java with examples

07-Mar-22 © 2021. Cavendish University. Rights Reserved 37


3. Object Oriented Programming | OOP

07-Mar-22 © 2021. Cavendish University. Rights Reserved 38


4. Array as first-class objects

// Display the first four cards


public class DeckOfCards {
for (int i = 0; i < 4; i++) {
public static void main(String[] args) {
String suit = suits[deck[i] / 13];
int[] deck = new int[52];
String rank = ranks[deck[i] %
String[] suits = {"Spades", "Hearts",
13];
"Diamonds", "Clubs"};
System.out.println("Card
String[] ranks = {"Ace", "2", "3", "4", "5", "6",
number " + deck[i] + ": " + rank + " of " +
"7", "8", "9", "10", "Jack", "Queen", "King"};
suit);
}
// Initialize the cards
for (int i = 0; i < deck.length; i++)
}
deck[i] = i;
}
// Display the first four cards
// Shuffle the cards
for (int i = 0; i < 4; i++) {
for (int i = 0; i < deck.length; i++) {
String suit = suits[deck[i] / 13];
// Generate an index randomly
String rank = ranks[deck[i] %
int index = (int)(Math.random() *
13];
deck.length);
System.out.println("Card
int temp = deck[i];
number " + deck[i] + ": " + rank + " of " +
deck[i] = deck[index];
suit);
deck[index] = temp;
}
}
DeckOfCards.java
}
}
07-Mar-22 © 2021. Cavendish University. Rights Reserved 39
4. Array as first-class objects

In principle, A language construct is said to be a FirstClass value in that language


when there are no restrictions on how it can be created and used: when the
construct can be treated as a value without restrictions.

The best way to understand the principle of First Class to consider that arrays can
be:
• Named by variables.
• Passed as arguments to procedures.
• Returned as the results of procedures.
• Included in data structures.

Basically, it means that you can do with arrays everything that you can do with all
other elements in the programming language.

07-Mar-22 © 2021. Cavendish University. Rights Reserved 40


Thank You

© 2021. Cavendish University. Private and Confidential

You might also like