0% found this document useful (0 votes)
10 views15 pages

Module 4 Finale

Uploaded by

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

Module 4 Finale

Uploaded by

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

Module IV Object Oriented Approach

Learning Outcomes
 Define and distinguish the differences of procedural/ functional
approach and object-oriented approach
 Define and discuss object and methods.
 Create member functions/methods for the class.
 Construct Java programs using Objects and Classes platform.
 Evaluate the output of code fragments having member function
and access modifier

ASSESSMENT TASK
1. What is procedural programming?
2. What is object oriented programming?
3. What is object and member function?

Overview
In this chapter the students will learn to distinguish the differences of
procedural programming and object oriented programming. They will learn
how to create program member functions and access modifier.

Learning Content

Object-oriented programming is a programming paradigm that


uses abstraction (in the form of classes and objects) to create models based
on the real world environment. An object-oriented application uses a
collection of objects, which communicate by passing messages to request
services.

In procedural languages procedures are a sequence of imperative


statements, such as assignments, tests, loops and invocations of sub
procedures. These procedures are functions, which map arguments to
return statements.

Top Down Design is the design method used in procedural


programming which will start with a problem (procedure) and then
systematically break the problem down into sub problems (sub procedures).
This is called functional decomposition, which continues until a sub problem
is straightforward enough to be solved by the corresponding sub procedure.
The difficulties with this type of programming, is that software maintenance
can be difficult and time consuming. When changes are made to the main
procedure (top), those changes can cascade to the sub procedures of main,
and the sub-sub procedures and so on, where the change may impact all
procedures in the pyramid. One alternative to procedural programming is

39
Module IV Object Oriented Approach

object oriented programming. Object oriented programming is meant to


address the difficulties with procedural programming.
In object oriented programming, the main modules in a program are
classes, rather than procedures. The object-oriented approach lets the
programmer create classes and objects that model real world objects.

Defining a Class

<modifier> class <name>


{
<attributeDeclaration>*
<constructorDeclaration>*
<methodDeclaration>*
}

Where <modifier> is an access modifier, which may be combined with


other types of modifier.

public class StudentRecord


{
// sample code here
}

where,
● public - means that our class is accessible to other classes outside the
package
● class - this is the keyword used to create a class in Java
● StudentRecord - a unique identifier that describes our class

Object
An object is an instance of a class having states and behaviors. Example: A
monkey has states - color, name, breed as well as behaviors - climbing,
eating, sleeping.
A sample of a class is given below:

class monkey {
String breed;
int age;
String color;
void climbing()
{
Statement;
}
void eating()
{
Statement;

40
Module IV Object Oriented Approach

}
void sleeping()
{
Statement;
} }

A class can contain any of the following variable types.


 Local variables: Variables defined inside methods, constructors or
blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed when
the method has completed.
 Instance variables: Instance variables are variables within a class
but outside any method. These variables are initialized when the class
is instantiated. Instance variables can be accessed from inside any
method, constructor or blocks of that particular class.
 Class variables: Class variables are variables declared with in a
class, outside any method, with the static keyword.

Instance Variables
public class StudentRecord
{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
//we'll add more code here later
}
where, private here means that the variables are only accessible within the
class. Other objects cannot access these variables directly. We will cover
more about accessibility later.

METHODS and ATTRIBUTES


A Java method is a collection of statements that are grouped together to
perform an operation. When you call the System.out.println() method, for
example, the system actually executes several statements in order to
display a message on the console.
Creating Method:
Considering the following example to explain the syntax of a method:
public static int methodBooks(int x, int
y)
{
// body of the program
}
41
Module IV Object Oriented Approach

- public static is the modifier.


- int : return type
- methodBooks: name of the method
- x, y: formal parameters
- int x, int y: list of parameters or are the parameters
-
Method definition consists of a method header and a method body. The
same is shown below:
The syntax shown above includes:
 modifier: It defines the access type of the method and it is optional to
use.
 returnType: Method may return a value.
 nameOfMethod: This is the method name. The method signature
consists of the method name and the parameter list.
 Parameter List: The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method may
contain zero parameters.
 method body: The method body defines what the method does with
statements.
Example:
This method takes two parameters number1 and number2 and returns the
minimum between the two numbers:

public static int minFunction(int num1, int num2)


{
int minimum;
if (num1 > num2)
else
minimum = num1;
return minimum;
}

Method Calling
Two ways to call a method:
- method returns a value
- Returning nothing (no return value).

The process of method calling is simple. When a program invokes a method,


the program control gets transferred to the called method. This called
method then returns control to the caller in two conditions, when:
 return statement is executed.

42
Module IV Object Oriented Approach

 reaches the method ending closing brace.


Example:
class MinimumNum
{
public static int minimumFunction(int num1, int num2) //1st method
{
int min;
if (num1 > num2)
min = num2;
else
min = num1;
return min;
}
public static void main(String[] args)
{
MinimumNum ominNumber = new MinimumNum(); // declaration of an
object
int x = 8;
int y = 5;
System.out.println("The Minimum Value is: " +
ominNumber.minimumFunction(x,y));
// or it could be like this:
int z= minimumFunction (x,y);
System.out.println("The Minimum Value is: " + z);
}
}

Program Output: The Minimum Value is: 5

Accessor methods
– used to read values from our class variables (instance/static).
– usually written as:
get<NameOfInstanceVariable>
– It also returns a value.
public class StudentRecord {
private String name;
:
public String getName(){
return name;
}
}
where,
● public - means that the method can be called from objects outside
the class

43
Module IV Object Oriented Approach

● String - is the return type of the method. This means that the
method should
return a value of type String
● getName - the name of the method
● () - this means that our method does not have any parameters

Example
public class StudentRecord
{
private String name;
:
public double getAverage()
{
double result = 0;
result=(mathGrade+englishGrade+scienceGrade)/ 3;
return result;
}
}

Static methods
public class StudentRecord
{
private static int studentCount;
public static int getStudentCount()
{
return studentCount;
}
}

– where,
● public- means that the method can be called from objects outside
the class
● static-means that the method is static and should be called by
typing,
[ClassName].[methodName].
● int- is the return type of the method. This means that the method
should return a
value of type int
● getStudentCount- the name of the method
● ()- this means that our method does not have any parameters

Void Keyword
The void keyword allows us to create methods which do not return a value.

44
Module IV Object Oriented Approach

Below is an example of a void method pro gram which does not return any value.
class gradesRank
{
public static void graRank (double grade)
{
if (grade >= 1.50)
{
System.out.println("Rank: 1");
}
else if (grade >= 1.25)
{ System.out.println("Rank: 2");
}
else
{ System.out.println("Rank: 3");
}
}
public static void main(String[] args)
{ graRank(1.75);
}
} }

Passing Parameters by Value


Parameters can be passed by value or by reference. Passing Parameters by
Value means calling a method with a parameter. Through the argument
value is passed to the parameter. Below is an example of example of
passing parameter by value.

Example:
The value of the arguments remains the same even after the method
invocation.
public class switchValue
{
public static void switchMethod(int num1, int num2)
{
System.out.println("Before switching,the number 1 is:"+num1
+"number2="+num2);
// Switch number 1 with number 2
int three = num1;
num1 = num2;
num2 = three;
System.out.println("After switching the number 1 is: “+num1+"number2
="+num2);
}

45
Module IV Object Oriented Approach

public static void main(String[] args) // main method


{
int num1 = 30;
int num2 = 45;
System.out.println("Before switching, number1 = "+num1+ "and number2 ="
+num2);
// Invoke the switch Method
switchMethod (num1, num2);
System.out.println(“ Before and after Switching of two numbers would be the
same”);
System.out.println("After switching , number1= "+num1+" and number2 is "
+num2);
} }

Program Output
Before switching, number1= 30 and number2=45
Before switching, the number 1 is:30 number2=45
After switching the number 1 is: 45 number2=30
Before and after Switching of two numbers would be the same”
After switching, number1=30 and number2 is: 45

Creating an Object
A class provides the blueprints for objects. An object is created from a class.
In Java, the new key word is used to create new objects.
Three steps on how to create an object from a class
 Declaration: A variable declaration with a variable name with an
object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.

Example of creating an object is given below:

class dog
{
public dog (String name){
// This constructor has one parameter, name.
System.out.println(" the dog name is :" + name );
}

public static void main(String []args){


// Following statement would create an object myPuppy
dog myPuppy = new dog ( "BROWNIE!" );
}
}

46
Module IV Object Oriented Approach

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects.
Example:
public class doggy
{
int dogAge;
public doggy (String name)
{
// This constructor has one parameter, name.
System.out.println(" Doggy’s Name is :" + name );
}

public void setAge( int age )


{
dogAge = age;
}

public int getAge( )


{
System.out.println("Doggy's age is :" + dogAge );
return dogAge;
}

public static void main(String []args)


{
/* Object creation */
doggy myPuppy = new doggy ( "BROWNIE" );

/* Call class method to set DOGGY's age */


myPuppy.setAge( 2 );

/* Call another class method to get DOGGY's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.dogAge );
}
}

47
Module IV Object Oriented Approach

Class Variables – Static Fields


A class variable is used to share characteristics across all objects within a
class, also known as Static fields. Static variables can be accessed even
though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods


Class methods, similar to Class variables can be invoked without having an
instance of the class. Class methods are often used to provide global
functions for Java programs.

JAVA OBJECTS
The Object Class is the super class for all classes in Java.
Some of the object class methods are:
- Equals
- toString()
- wait()
- notify()
- notifyAll()
- hashcode()
- clone()
Object is an instance of a class created using a new operator. The new
operator returns a reference to a new instance of a class. This reference can
be assigned to a reference variable of the class. The process of creating
objects from a class is called instantiation. An object encapsulates state and
behavior.
Example:
public class Cube
{
int length = 10;
int breadth = 10;
int height = 10;
public int getVolume()
{
return (length * breadth * height);
}
public static void main(String[] args)
{
Cube cubeObj; // Creates a Cube Reference
cubeObj = new Cube(); // Creates an Object of Cube
System.out.println("Volume of Cube is : " +
cubeObj.getVolume());
} }
Abstract classes are classes that contain one or more abstract methods. An
abstract method is a method that is declared, but contains no

48
Module IV Object Oriented Approach

implementation. Abstract classes may not be instantiated, and


require subclasses to provide implementations for the abstract methods.
An abstract method is a method that is declared without an implementation
(without braces, and followed by a semicolon).
Example:
abstract void moveTo(double deltaX, double deltaY).
Below is an example of an abstract that has abstract method
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
} }
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
} }
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
getShape() method
s.draw();
} }

Abstract Classes Compared to Interfaces


Abstract classes are similar to interfaces. They may contain a mix of methods
declared with or without an implementation and it cannot instantiate them.
With abstract classes, fields that are not static and final can be declared, and
define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all
methods declared or defined (as default methods) are public.

Which should you use, abstract classes or interfaces?

 Using abstract classes


o You want to share code among several closely related classes.

49
Module IV Object Oriented Approach

o You expect that classes that extend your abstract class have
many common methods or fields, or require access modifiers
other than public (such as protected and private).
o You want to declare non-static or non-final fields. This enables
you to define methods that can access and modify the state of
the object to which they belong.
 Using interfaces
o You expect that unrelated classes would implement your
interface. For example, the interfaces Comparable and Clone
able are implemented by many unrelated classes.
o You want to specify the behavior of a particular data type, but
not concerned about who implements its behavior.
o You want to take advantage of multiple inheritance of type.

INTERFACES
What is an interface?
Interface looks like class but it is not a class. An interface can have methods
and variables just like the class but the methods declared in interface are by
default abstract (only method signature, no body). Also, the variables
declared in an interface are public, static & final by default. We will discuss
these points in detail, later in this post.

What is the use of interfaces?


Interfaces are used for abstraction. Interfaces have to be implemented by the
class before it can access the interfaces because it does not have body. The
class that implements interface must implement all the methods of that
interface. Interfaces are declared by specifying a keyword “interface”.

Below is Interfaces syntax;


interface MyInterface
{
/* All the methods are public abstract by default
* Note down that these methods are not having body
*/
public void method1();
public void method2();
Below is an example program of Interfaces
}

50
Module IV Object Oriented Approach

Sample Program
interface SampleInterface
{
public void FirstMethod();
public void SecondMethod();
}
class mySampleInterface implements SampleInterface
{
public void FirstMethod ()
{
System.out.println("Welcome to Java Classes!");
}
public void SecondMethod()
{
System.out.println("Implementation of Interfaces in Java
Classes");
}
public static void main(String arg[])
{
SampleInterface ointer = new mySampleInterface ();
ointer.FirstMethod();
ointer.SecondMethod();
} }

Implementation of Interfaces in Java Classes


Modifiers are keywords that you add to those definitions to change their
meanings. The Java language has a wide variety of modifiers, including the
following:

 Java Access Modifiers


 Non Access Modifiers
public class className
{
// ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
//body of method
}

Access Control Modifiers:


Java provides a number of access modifiers to set access levels for classes,
variables, methods and constructors. The four access levels are:

51
Module IV Object Oriented Approach

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve other
functionality.
 The static modifier for creating class methods and variables
 The final modifier for finalizing the implementations of classes,
methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.
A Java method is a collection of statements that are grouped together to
perform an operation. When you call the System.out.println() method, for
example, the system actually executes several statements in order to
display a message on the console.

Now you will learn how to create your own methods with or without return
values, invoke a method with or without parameters, and apply method
abstraction in the program design.

Exercises

1. Tracing an Error: Trace the program below and determine the error.
public class sAMPLEprogram {
public static void main(String[] args)
{
Square mysQ;
mysQ.height = 25;
mysQ.width = 25;
System.out.println("the area of square is " + mysQ.area());
}
}

2. Consider the following code snippet:

public class sample Program {


public static int a = 10;
public int b = 5;
}

a. What are the instance variables?

b. What are the class variables?

3. Determine the output from the following code snippet:

IdentifyMyProgram program = new IdentifyMyProgram();

52
Module IV Object Oriented Approach

IdentifyMyProgram myprogram= new IdentifyMyProgram ();


program.a = 7;
myprogram.a = 16;
program.b = 12;
myprogram.b =12;
System.out.println("program.b = " + program.b);
System.out.println("myprogram.b = " + myprogram.b);
System.out.println("program.a = " + program.a);
System.out.println("myprogram.a = " + myprogram.a);
System.out.println("IdentifyMyProgram.a = " +
IdentifyMyProgram.a);

4. Write a simple program that uses an instance variables and methods. In


the main method create two(2) objects to call or display the output of the
methods.

References
Singh, Chaitanya. BeginnersBook. 2019. Retrieved from
https://beginnersbook.com/2013/05/method-overloading/

ProgramCreek. 2019. Overriding vs.Overloading. Retrieved from


https://www.programcreek.com/

JavaPoint. Method Overloading in Java.2018. Retrieved from


https://www.javatpoint.com/method-overloading-in-java

Gangvany, Monica. Quora. (2018). Retrieved from


https://www.quora.com/What-are-the-characteristics-of-java

WIKIBOOKS. Primitive Types. (2018). Retrieved from


https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types
Tutorialspoint.Java Access Modifier. (2019). Retrieved from
https://www.tutorialspoint.com/java/java_access_modifiers.htm

W3Resource. Java Class, methods, instance variables.(2018). Retrieved from


https://www.w3resource.com/java-tutorial/java-class-methods-instance-
variables.php

53

You might also like