COM323 Programmingin Java Week 02
COM323 Programmingin Java Week 02
// 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;
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);
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
import java.util.Scanner;
• Abstraction
• Polymorphism
• Inheritance
• Encapsulation
https://www.youtube.com/watch?v=pTB0EiLXUC8
https://www.youtube.com/watch?v=m_MQYyJpIjg&list=RDLVpTB0EiLXUC8&index=4
• Abstraction A
• Polymorphism
• Inheritance
• Encapsulation
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
Encapsulation
Encapsulation in Java:
Polymorphism
Polymorphism in Java:
▪ 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).
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
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
implement
In the example below, you can see an abstract class called Animal with two
abstract and one concrete method.
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
}
}
Now, test it with the TestBird and TestFish classes. Both call the one
concrete (label()) and the two abstract (move() and eat()) methods.
myBird.label(); myFish.label();
myBird.move(); myFish.move();
myBird.eat(); myFish.eat();
} }
} }
TestFish.java
TestBird.java
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();
}
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.
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();
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
The TestAnimal class first sets a value for each field with the setter methods, then
prints out the values using the getter methods.
myAnimal.setName("Eagle");
myAnimal.setAverageWeight(1.5);
myAnimal.setNumberOfLegs(2);
TestAnimal2.java
Adapted from: 6 OOP concepts in Java with examples
ENCAPSULATION ABSTRACTION
Bird Animal
myAnimal
Animal2
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.
Bird3
extends
extends
Eagle3
“Instantiate”
myEagle
Derived class
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";
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();
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.
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
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
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.");
}
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();
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.