0% found this document useful (0 votes)
12 views62 pages

1a - CSC584 - Overview of OOP - Part 1

This document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, focusing on Java programming. It covers fundamental topics such as objects, classes, inheritance, polymorphism, and access levels, as well as practical examples and quizzes to reinforce understanding. Additionally, it discusses different Java editions and popular Integrated Development Environments (IDEs) for Java development.

Uploaded by

2023268792
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views62 pages

1a - CSC584 - Overview of OOP - Part 1

This document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, focusing on Java programming. It covers fundamental topics such as objects, classes, inheritance, polymorphism, and access levels, as well as practical examples and quizzes to reinforce understanding. Additionally, it discusses different Java editions and popular Integrated Development Environments (IDEs) for Java development.

Uploaded by

2023268792
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

CHAPTER 1 -

REVIEW OF
OBJECT
ORIENTED
PROGRAMMING
CONCEPTS
CSC584 - ENTERPRISE PROGRAMMING
REVIEW OF OBJECT ORIENTED
PROGRAMMING CONCEPTS
1. Objects, classes, packages
2. Inheritance & Polymorphism concept
3. Inheriting instances fields and methods
4. Method overriding
5. Access levels – public, protected, private
6. Abstract super classes and methods
7. Interface
INTRODUCTION TO JAVA - WHY JAVA?
2017 2024
INTRODUCTION TO JAVA - WHY JAVA?
❖Java enables users to develop and deploy applications on the
Internet for servers, desktop computers, and small hand-held
devices.
❖Java is a general purpose programming language.
❖Java is the Internet programming language.
❖Java can be used to develop Web applications.
JDK EDITIONS
▪ Java Standard Edition (JSE)
▪ JSE can be used to develop and deploy Java applications
on desktops and servers.
(https://www.oracle.com/java/technologies/java-se-glance.html)

▪ Java Enterprise Edition (JEE)


▪ JEE can be used to develop server-side applications such as Java
servlets and Java ServerPages.
(https://www.oracle.com/technetwork/java/javaee/overview/index.html)

▪ Java Micro Edition (JME).


▪ JME can be used to develop applications for mobile devices such
as cell phones, TV set-top boxes.
(https://www.oracle.com/technetwork/java/embedded/javame/index.html)
POPULAR JAVA IDE(S)
▪ NetBeans Open Source by Sun
▪ Eclipse Open Source by IBM
▪ Intellij IDEA
OBJECTS,
CLASSES &
PACKAGES
OO PROGRAMMING CONCEPTS
▪ Object-oriented programming (OOP) involves
programming using objects.
▪ An object represents an entity in the real world that can be
distinctly identified.
▪ For example, a student, a desk, a circle, a button, and
even a loan can all be viewed as objects.
▪ An object has a unique identity, state, and behaviors.
OO PROGRAMMING CONCEPTS
▪ The state of an object consists of a set of data fields (also
known as properties) with their current values.
▪ The behavior of an object is defined by a set of methods.
OBJECTS

An object has both a state and behavior. The state


defines the object, and the behavior defines what the
object does.
CLASSES
▪ Classes are constructs that define objects of the
same type.
▪ A Java class uses variables to define data fields and
methods to define behaviors.
▪ A class provides a special type of methods, known
as constructors, which are invoked to construct
objects from the class.
CLASSES
UML CLASS DIAGRAM
CONSTRUCTORS
Circle() { Constructors are a special kind of
} methods that are invoked to construct
objects.
Circle(double newRadius) {
radius = newRadius;
}
CONSTRUCTORS, CONT.
▪ A constructor with no parameters is referred to as a no-arg
constructor.
▪ Constructors must have the same name as the class itself.
▪ Constructors do not have a return type—not even void.
▪ Constructors are invoked using the new operator when an
object is created. Constructors play the role of initializing
objects.
CREATING OBJECTS USING
CONSTRUCTORS
new ClassName();

Example:
new Circle();

new Circle(5.0);
DEFAULT CONSTRUCTOR
▪ A class may be declared without constructors.
▪ A no-arg constructor with an empty body is
implicitly declared in the class.
▪ This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
DECLARING OBJECT REFERENCE
VARIABLES
▪ To reference an object, assign the object to a reference
variable.

▪ To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;
DECLARING/CREATING OBJECTS
IN A SINGLE STEP
ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example
Circle myCircle = new Circle();
ACCESSING OBJECTS
▪ Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

▪ Invoking the object’s method:


objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
Nouns
State/Properties Representation in Java
Black Hair hairColor =“black”
Brown Eyes eyeColor = “brown”
Object 160 cm height = 160
50 kg weight = 50

Behavior/Method Representation in Java


Eat eat()
Sleep sleep()
Person Walk walk()
Study study()
Play play()

Verbs
QUIZ
What's wrong with the following program? Fix the SomethingIsWrong class shown below.

public class SomethingIsWrong {

public static void main(String[] args) {

Rectangle myRect;
myRect.width = 40;
myRect.height = 50;
System.out.println("myRect's area is " + myRect.area());

}
QUIZ
Given the following class, write a class named NumberDisplay that creates an instance of the
class, initializes its two member variables, and then displays the value of each member
variable.

public class Number{

public int anInt;


public float aFloat;

}
INHERITANCE & POLYMORPHISM
CONCEPT
INHERITANCE
▪ A process in which a new class is derived from an existing one.
▪ Parent class/super class: existing class.
▪ Child class/sub class: derived class.

▪ Child inherits characteristics of the parent - methods and data defined


by the parent class.
▪ Can tailor a derived class as needed by adding new variables or
methods, or by modifying the inherited ones.
INHERITANCE
▪ Inheritance relationships are shown in a UML class diagram using a
solid arrow with an unfilled triangular arrowhead pointing to the
parent class

Vehicle

Car

▪ Proper inheritance creates an is-a relationship, meaning the child is a


more specific version of the parent
DERIVING SUBCLASSES

▪ In Java, we use the reserved word extends to establish an inheritance


relationship

public class Car extends Vehicle


{
// class contents
}
SIMPLE EXAMPLE : INHERITANCE

▪ We can effectively model similar, but


different types of objects using Pet

inheritance
▪ Suppose we want to model rabbit and
cat. They are different types of pets. We
can define the Pet class and the Rabbit
and Cat classes as the subclasses of the
Pet class. Rabbit Cat
THE PET CLASS
class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String petName) {
name = petName;
}
public String speak( ) {
return “I’m your cuddly little pet.”;
}
}
SUBCLASSES OF THE PET CLASS
class Cat extends Pet { The Cat subclass overrides
public String speak( ) { the inherited method speak.
return “Don’t give me orders.\n” +
“I speak only when I want to.”;
}
}

class Rabbit extends Pet {


public String fetch( ) {
The Rabbit subclass adds
return “Yes, master. Fetch I will.”;
a new method fetch.
}
}
SAMPLE USAGE OF THE SUBCLASSES
Rabbit myRabbit = new Rabbit();
I’m your cuddly little pet.
Yes, master. Fetch I will.
System.out.println(myRabbit.speak());
System.out.println(myRabbit.fetch());

Cat myCat = new Cat();


Don’t give me orders.
System.out.println(myCat.speak()); I speak only when I want to.
System.out.println(myCat.fetch()); ERROR
DEFINING CLASSES WITH INHERITANCE

▪ Case Study:
▪ Suppose we want to implement a class roster that contains both
undergraduate and graduate students.
▪ Each student’s record will contain his or her name, three test
scores, and the final course grade.
▪ The formula for determining the course grade is different for
graduate students than for undergraduate students.
MODELING TWO TYPES OF
STUDENTS

▪ There are two ways to design the classes to model undergraduate


and graduate students.
▪ We can define two unrelated classes, one for undergraduates and
one for graduates.
▪ We can model the two kinds of students by using classes that are
related in an inheritance hierarchy.
▪ Two classes are unrelated if they are not connected in an inheritance
relationship.
CLASSES FOR THE CLASS ROSTER

▪ For the Class Roster sample, we design three classes:


▪ Student
▪ UndergraduateStudent
▪ GraduateStudent

▪ The Student class will incorporate behavior and data common to


both UndergraduateStudent and GraduateStudent objects.
▪ The UndergraduateStudent class and the GraduateStudent class
will each contain behaviors and data specific to their respective
objects.
CLASSES FOR THE CLASS ROSTER -
CREATING THE ROSTER ARRAY
▪ We can maintain our class roster using an array, combining objects
from the Student, UndergraduateStudent, and GraduateStudent
classes.

Student roster = new Student[40];


. . .
roster[0] = new GraduateStudent();
roster[1] = new UndergraduateStudent();
roster[2] = new UndergraduateStudent();
. . .
CLASSES FOR THE CLASS ROSTER -
STATE OF THE ROSTER ARRAY
▪ Theroster array with elements referring to instances of
GraduateStudent or UndergraduateStudent classes.
CLASSES FOR THE CLASS ROSTER -
SAMPLE POLYMORPHIC MESSAGE
▪ To compute the course grade using the roster array, we execute

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


roster[i].computeCourseGrade();
}

• If roster[i] refers to a GraduateStudent, then the computeCourseGrade method of the


GraduateStudent class is executed.
• If roster[i] refers to an UndergraduateStudent, then the computeCourseGrade method
of the UndergraduateStudent class is executed.
THE SUPER REFERENCE

▪ Unlike members of a superclass, constructors of a superclass are not


inherited by its subclasses even though they have public visibility.
▪ The super reference can be used to refer to the parent class, and
often is used to invoke the parent's constructor.
▪A child’s constructor is responsible for calling the parent’s
constructor.
▪ The first line of a child’s constructor should use the super reference
to call the parent’s constructor.
▪ The super reference can also be used to reference other variables
and methods defined in the parent’s class.
EXAMPLE: USING SUPER KEYWORD
public class Bicycle {
public int cadence;
public int gear;
public int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear){


super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
ACCESSING SUPERCLASS MEMBER

▪ If your method overrides one of its superclass's methods, you can


invoke the overridden method through the use of the keyword super.
▪ You can also use super to refer to a hidden field.
EXAMPLE: USING SUPER KEYWORD
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}

public class Subclass extends Superclass {


public void printMethod() { //overrides printMethod in Superclass
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
What is the output?
QUIZ
What is the output?
Animal.java Cat.java
public class Animal{ public class Cat extends Animal{
String color="white"; String color="brown";
} public void printColor(){
System.out.println(color);
System.out.println(super.color);
}
}

TestSuper1.java

public class TestSuper1{


public static void main(String args[]){
Cat c=new Cat();
c.printColor();
}
}
QUIZ
What is the output?

Animal.java Cat.java
public class Animal{ public class Cat extends Animal{
Animal(){ Cat(){
System.out.println("Animal is created"); super();
} System.out.println("Cat is created");
} }
}

TestSuper2.java
public class TestSuper2{
public static void main(String args[]){
Cat c=new Cat();
}
}
OVERRIDING METHODS
▪ A child class can override the definition of an inherited method in
favor of its own.
▪ The new method must have the same signature as the parent's
method, but can have a different body.
▪ The type of the object executing the method determines which
version of the method is invoked.
OVERRIDING
▪ A method in the parent class can be invoked explicitly using the
super reference
▪ If a method is declared with the final modifier, it cannot be
overridden
▪ The concept of overriding can be applied to data and is called
shadowing variables
▪ Shadowing variables should be avoided because it tends to cause
unnecessarily confusing code
OVERLOADING VS. OVERRIDING

▪ Overloading deals with multiple methods with the same name in the
same class, but with different signatures
▪ Overriding deals with two methods, one in a parent class and one in a
child class, that have the same signature
▪ Overloading lets you define a similar operation in different ways for
different parameters
▪ Overriding lets you define a similar operation in different ways for
different object types
EXAMPLE: METHOD OVERLOADING
class Sample{
public static void main(String args[]){
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}

class DisplayOverloading{
public void disp(char c){
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}
CLASS HIERARCHIES
▪ A child class of one parent can be the parent of another child, forming
a class hierarchy.
CLASS HIERARCHIES
▪ Two children of the same parent are called siblings.

▪ Common features should be put as high in the hierarchy as is


reasonable.
▪ An inherited member is passed continually down the line.

▪ Therefore, a child class inherits from all its ancestor classes.


POLYMORPHISM
▪ Polymorphism allows a single variable to refer to objects from
different subclasses in the same inheritance hierarchy
▪ For example, if Cat and Rabbit are subclasses of Pet, then the following
statements are valid:

Pet myPet;
Pet

myPet = new Rabbit();


. . .
Rabbit Cat
myPet = new Cat();
THE INSTANCEOF OPERATOR
▪ The instanceof operator can help us learn the class of an object (i.e.
test whether the object is an instance of the specified type (class or
subclass or interface))

class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
THE INSTANCEOF OPERATOR
▪ An object of subclass type is also a type of parent class.
▪ For example, if Cat extends Animal then object of Cat can be
referred by either Cat or Animal class.

class Animal{}
class Cat1 extends Animal{//Cat inherits Animal
public static void main(String args[]){
Cat1 c=new Cat1();
System.out.println(c instanceof Animal);//true
}
}
THE INSTANCEOF OPERATOR
▪ The following code counts the number of undergraduate students.

int undergradCount = 0;
for (int i = 0; i < numberOfStudents; i++) {
if ( roster[i] instanceof UndergraduateStudent
) {
undergradCount++;
}
}
INSTANCEOF: EXAMPLE
▪ Suppose you have four classes which are Animal
Animal, Mammal, Reptile, and Dolphin as
shown. This can be translated into the
following:
public class Animal{
Mammal Reptile
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
Dolphin
public class Dolphin extends Mammal{
}

Now, based on the above example, In Object Oriented terms, the


following are true:
· Animal is the superclass of Mammal class.
· Animal is the superclass of Reptile class.
· Mammal and Reptile are subclasses of Animal class.
· Dolphin is the subclass of both Mammal and Animal classes.
INSTANCEOF: EXAMPLE CONT…
▪ Now, if we consider the IS-A relationship, we can say:
· Mammal IS-A Animal
· Reptile IS-A Animal
· Dolphin IS-A Mammal
· Hence : Dolphin IS-A Animal as well

▪ With use of the extends keyword the subclasses will be able to


inherit all the properties of the superclass except for the private
properties of the superclass.
INSTANCEOF: EXAMPLE CONT…
public class Test {

public static void main(String args[]){


Animal a = new Animal();
Mammal m = new Mammal();
Dolphin d = new Dolphin ();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

What is the output?


Animal
INSTANCEOF: EXAMPLE CONT…
Mammal Reptile
Given the following:

Animal animal = new Animal(); Dolphin Turtle Snake

Mammal mammal = new Mammal();


Reptile reptile = new Reptile(); QUESTION:
Animal t = new Turtle(); a) Is animal instanceof Animal?
Animal s = new Snake(); b) Is t instanceof Turtle?
Animal d = new Dolphin(); c) Is mammal instanceof Animal?
d) Is t instanceof Mammal?
e) Is d instanceof Reptile?
f) Is mammal instanceof Mammal?
g) Is reptile instanceof Animal?
INHERITANCE AND MEMBER
ACCESSIBILITY
▪ We use the following visual representation of inheritance to illustrate
data member accessibility.

Instances

This shows the inherited


components of the
superclass are part of
the subclass instance

Class Hierarchy
THE EFFECT OF THREE VISIBILITY
MODIFIERS package
one

package
two
ACCESSIBILITY OF SUPER FROM SUB
▪ Everything except the private members of the Super class is visible
from a method of the Sub class.
ACCESSIBILITY FROM ANOTHER
INSTANCE
▪ Data members accessible from an instance are also accessible from
other instances of the same class.

You might also like