You are on page 1of 84

1

MORE ON OOP CONCEPTS

4/6/2024 OOP- CH-2- More on OOP Concepts


Contents
1. Overview
2. Class declaration and Objects instantiation
3. Static and Instance members
4. Methods and their components
5. Constructors (Default, parameterized and
Overloaded)
6. Access modifiers
7. Accessors and Mutators
8. Array ad String

4/6/2024
Overview
 Most important basic elements for programming
languages are:
 Programming Environment
 Data Types, Variables, Keywords

 Logical and Arithmetical Operators

 If else conditions

 Loops

 Numbers, Characters and Arrays

 Methods

 Input and Output Operations


4/6/2024
Class declaration and Objects instantiation
4

 The class declaration component declares the


name of the class along with other attributes
and whether the class is public, final, or
abstract.
 At minimum, the class declaration must contain
the class keyword and the name of the class that
you are defining.
 Thus the simplest class declaration that you can
write looks like this:
4/6/2024
5

[modifiers] class NameOfClass {


...
}
◼ Example
public class Rectangle{
...
}
 modifiers declare whether the class is abstract, final or
public
 Class names must be a legal Java identifier and, by
convention, begin with a capital letter.
4/6/2024
6

 Creating objects
A class provides the blueprint for objects: you create an
object from a class.
◼ In Java, you create an object by creating an instance of a
class or, in other words, instantiating a class.
 Often, you will see a Java object created with a
statement like this one:
Rectangle r1= new Rectangle();
 This single statement actually performs three actions:
declaration, instantiation, and initialization.
4/6/2024
7

 Declaring an object
◼ Declaring a variable to hold an object is just like declaring a
variable to hold a value of primitive type: type name
Rectangle r1;
 Instantiating an Object
◼ The new operator instantiates a class by allocating memory
for a new object of that type.
new Rectangle();
 Initializing an Object
Rectangle r1= new Rectangle();

4/6/2024
Instance and Static members
8

 Instance members
 Each object created will have its own copies of the
fields defined in its class. The fields of an object are
called instance variables.
 The methods of an object define its behavior. These
methods are called instance methods. It is important to
note that these methods pertain to each object of the
class.
 Instance variables and instance methods, which belong
to objects, are collectively called instance members.

4/6/2024
9

 Example
int cal;
float min=1;
void display(int x)
{
….
}

4/6/2024
10

 Static members
 Methods and variables defined inside the class are called
an instance methods and instance variables. That is, a
separate copy of them is created upon creation of each
new object.
 But in some cases it si necessary to define a member that is
common to all the objects and accessed without using a
particular object.
 That is, the member belongs to the class as a whole rather
than the objects created form the class. Such members can
be created by preceding them with the keyword static.

4/6/2024
11

 Example
 static int cal;
 static float min=1;

 static void display (int x) { …}

 When a member is declared static, it can be


accessed before any objects of its class are
created, and without reference to any object.
 We can declare both method and variables to be
static
4/6/2024
12

 The most common example of static member is


main(). main() is declared as static because it must
be called before any objects exist.
 Instance variables declared as static are, essentially
global variables.
 Restrictions to static
 They can only call other static methods
 They must only access static data

 They can’t refer to this or super in any way

4/6/2024
Instance and Static Variables
13

 Instance variables
 Instance variables are declared in a class, but outside a
method, constructor or any block.
 Instance variables are created when an object is created
with the use of the keyword 'new' and destroyed when the
object is destroyed.
 Instance variables can be accessed directly by calling the
variable name inside the class.
◼ However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name.
◼ ObjectReference.VariableName.

4/6/2024
14

 Instance variables hold values that must be referenced


by more than one method, constructor or block, or
essential parts of an object's state that must be present
throughout the class.
 Example
◼ Obj1.cal=10;
◼ Obj1.min=2;
◼ Obj1.display(5);

4/6/2024
15

 Static (class) variables


 Class variables also known as static variables are
declared with the static keyword in a class, but
outside a method, constructor or a block.
 Static variables are created when the program starts
and destroyed when the program stops.
 Static variables can be accessed by calling with the
class name ClassName.VariableName.
 There would only be one copy of each class variable
per class, regardless of how many objects are created
from it.

4/6/2024
16

 Example:
 Class_name.cal=10;

 Class_name.min=2;

 Class_name.display(4);

4/6/2024
Methods and their components
17

 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.

4/6/2024
18

 Creating Method
 Considering the following example to explain the syntax of a method −
 Syntax
[modifier] returnType nameOfMethod ([Parameter List])
{ // method body }
 Here,
◼ 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 the
statements.

4/6/2024
19

 Example

4/6/2024
20

 Method Calling
 Forusing a method, it should be called. There are two
ways in which a method is called i.e., method returns a
value or 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 −
◼ the return statement is executed.
◼ it reaches the method ending closing brace.

4/6/2024
21

 Passing Parameters by Value


 While working under calling process, arguments is to be
passed.
 These should be in the same order as their respective
parameters in the method specification.
 Parameters can be passed by value or by reference.
◼ Passing
Parameters by Value means calling a method with a
parameter. Through this, the argument value is passed to the
parameter.

4/6/2024
22

 Method Overloading
 When a class has two or more methods by the same
name but different parameters, it is known as method
overloading.
◼ Itis different from overriding. In overriding, a method has
the same method name, type, number of parameters, etc.
 Example

4/6/2024
23

4/6/2024
Constructor
24

 A constructor initializes an object immediately upon


creation
 It has the same name as the class in which it resides and
it is syntactically similar to a method.
 Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
 Constructors look a little strange because they have
no return type, not even void.

4/6/2024
25

 All classes have constructors, whether you define one or


not, because Java automatically provides a default
constructor that initializes all member variables to zero.
 However, once you define your own constructor, the
default constructor is no longer used.
 Syntax
 Following is the syntax of a constructor −
class ClassName {
ClassName() { }
}

4/6/2024
26

 Java allows two types of constructors namely −


 No argument Constructors
◼ As the name specifies the no argument constructors of Java
does not accept any parameters instead, using these
constructors the instance variables of a method will be
initialized with fixed values for all objects.
 Parameterized Constructors
◼ Most often, you will need a constructor that accepts one or
more parameters. Parameters are added to a constructor in
the same way that they are added to a method, just declare
them inside the parentheses after the constructor's name.

4/6/2024
27

 Example

4/6/2024
28

 The ‘this’ keyword


 Many times it is necessary to refer to its own object in a
method or a constructor.
 To allow this java defines the ‘this’ keyword.

 The ‘this’ is used inside the method or constructor to


refer its own object.
 That is, ‘this’ is always a reference to the object of the
current class’ type

4/6/2024
29

 Example

4/6/2024
Exercise 1:
30

 Create a class "House", with an attribute “length”,


“width”, "area", a constructor that sets there values
and a method "ShowData" to display "I am a
house, my area is xxx m2 (instead of xxx, it will
show the real surface).
 Write a second class to test your House class:
TestClass.
 The second class should allow the user to input length
and width of the house.
 Display the area of the house using ShowData method.

4/6/2024
Exercise 2:
31

 Write a Java program that accept two integers and


return true if either one is 5 or their sum or difference is
5.
 Class name: Program2, TestProgram2(Main method)
 Attributes: number1 and number2
 Method: checkIf5
◼ Sample Output:
Enter the first number: 5
Enter the second number: 3
True

Enter the first number: 3


Enter the second number: 4
False

4/6/2024
Exercise 3:
32

 Write a Java program to check if it is possible to add two


integers to get the third integer from three given integers
 Class name: Program3, TestProgram3(Main method)
 Attributes: number1 , number2 and number3
 Method: checkIfPossible
◼ Sample Output:
Enter the first number: 5
Enter the second number: 3
Enter the third number: 2
True

Enter the first number: 3


Enter the second number: 4
Enter the third number: 5
False
4/6/2024
Exercise 4:
33

 Write a Java program to check if two or more non-negative


given integers have the same rightmost digit.
 Class name: Program4 , TestProgram4(Main method)
 Attributes: number1 , number2 and number3
 Method: checkRigtmostDigit
◼ Sample Output:
Enter the first number: 50
Enter the second number: 30
Enter the third number: 20
True

Enter the first number: 31


Enter the second number: 43
Enter the third number: 52
False

4/6/2024
Exercise 5:
34

 Write a Java program to calculate the area of the


rectangle.
 Class name: Program5 , TestProgram5(Main method)
 Attributes: length, width
 Method: caculateArea, getLength, getWidth, setLength,
setWidth
◼ Sample Output:
Enter the length of the rectangle: 6
Enter the width of the rectangle: 7
******************************
The length of the rectangle is: 6
The width of the rectangle is: 7
The area of the rectangle is: 42
4/6/2024
Exercise 6:
35

 Write a Java program to check which number


nearest to the value 100 among two given integers.
Return 0 if the two numbers are equal.
 Class name: Program6 , TestProgram6(Main method)
 Attributes: number1, number2

 Method: checkNearest
◼ Sample Output:
Enter the first number: 89
Enter the second number: 92
92

4/6/2024
Contents
1. Overview
2. Class declaration and Objects instantiation
3. Static and Instance members
4. Methods and their components
5. Constructors (Default, parameterized and
Overloaded)
6. Access modifiers
7. Accessors and Mutators
8. Array ad String

4/6/2024
Access Modifiers
37

 An access modifier restricts the access of a class,


constructor, data member and method in another
class.
 In java we have four access modifiers:
1. default
2. private
3. protected
4. public

4/6/2024
38

 Default access modifier


 When we do not mention any access modifier, it is
called default access modifier.
 The scope of this modifier is limited to the package
only.
◼ Thismeans that if we have a class with the default access
modifier in a package, only those classes that are in this
package can access this class.
◼ No other class outside this package can access this class.

4/6/2024
Example
39

4/6/2024
40 4/6/2024
41

 Private access modifier


 The scope of private modifier is limited to the class
only.
 Private Data members and methods are only accessible
within the class
 Class and Interface cannot be declared as private

 If a class has private constructor then you cannot


create the object of that class from outside of the class.

4/6/2024
Example
42

4/6/2024
43

 Protected Access Modifier


 Protected data member and method are only
accessible by the classes of the same package and
the subclasses present in any package.
 You can also say that the protected access modifier is
similar to default access modifier with one exception
that it has visibility in sub classes.
 Classes cannot be declared protected. This access
modifier is generally used in a parent child relationship.

4/6/2024
44 4/6/2024
45

 Public access modifier


 Themembers, methods and classes that are declared
public can be accessed from anywhere. This modifier
doesn’t put any restriction on the access.

4/6/2024
46 4/6/2024
47 4/6/2024
Contents
1. Overview
2. Class declaration and Objects instantiation
3. Static and Instance members
4. Methods and their components
5. Constructors (Default, parameterized and
Overloaded)
6. Access modifiers
7. Accessors and Mutators
8. Array ad String

4/6/2024
Accessors and Mutators
49

 In Java accessors are used to get the value of a


private field and mutators are used to set the
value of a private field.
 Accessors are also known as getters and mutators
are also known as setters.
 Ifwe have declared the variables as private then they
would not be accessible by all so we need to use getter
and setter methods.

4/6/2024
50

 Accessors
 An Accessor method is commonly known as a get
method or simply a getter.
 They are declared as public.
◼A naming scheme is followed by accessors, in other words
they add a word to get in the start of the method name.
 They are used to return the value of a private field.
 The same data type is returned by these methods
depending on their private field.

4/6/2024
51

 Example

4/6/2024
52

 Mutator
 A Mutator method is commonly known as a set method or
simply a setter.
◼ A Mutator method mutates things, in other words change things. It
shows us the principle of encapsulation.
 They are also known as modifiers. They are easily spotted
because they started with the word set.
 They are declared as public.
 Mutator methods do not have any return type and they
also accept a parameter of the same data type depending
on their private field. After that it is used to set the value of
the private field.

4/6/2024
53

 Example

4/6/2024
Contents
1. Overview
2. Class declaration and Objects instantiation
3. Static and Instance members
4. Methods and their components
5. Constructors (Default, parameterized and
Overloaded)
6. Access modifiers
7. Accessors and Mutators
8. Array ad String

4/6/2024
Array in Java
55

 Java provides a data structure, the array, which


stores a fixed-size sequential collection of elements
of the same type.
 An array is used to store a collection of data, but it is
often more useful to think of an array as a collection
of variables of the same type.
 Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored
on 1st index and so on.

4/6/2024
56

 Declaring Array Variables


 To use an array in a program, you must declare a
variable to reference the array, and you must specify
the type of array the variable can reference.
 Here is the syntax for declaring an array variable
Syntax
dataType [] arrayRefVar; // preferred way. or
dataType arrayRefVar []; //works but not preferred way.
Example
double[] myList; or double myList[];

4/6/2024
57

 Creating Arrays
 You can create an array by using the new operator with
the following syntax −
 Syntax
arrayRefVar = new dataType[arraySize];
 The above statement does two things −
◼ It creates an array using new dataType[arraySize].
◼ It assigns the reference of the newly created array to the
variable arrayRefVar.

4/6/2024
58

 Declaring an array variable, creating an array, and


assigning the reference of the array to the variable can
be combined in one statement, as shown below
dataType[] arrayRefVar = new dataType[arraySize];
 Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
 The array elements are accessed through the index.
 Array indices are 0-based; that is, they start from 0
to arrayRefVar.length-1.

4/6/2024
59

 Example
 Following statement declares an array variable, myList,
creates an array of 10 elements of double type and
assigns its reference to myList −
double[] myList = new double[10];
 Following picture represents array myList. Here, myList
holds ten double values and the indices are from 0 to 9.

4/6/2024
60

4/6/2024
61

 Using an Array Initializer


 You can create an array and initialize its elements with an
array initializer—a comma-separated list of expressions
(called an initializer list) enclosed in braces.
 In this case, the array length is determined by the number of
elements in the initializer list.
 For example,

◼ creates a five-element array with index values 0–4. Element n[0]


is initialized to 10, n[1] is initialized to 20, and so on.

4/6/2024
62

 Array Length
 InJava, the array length is the number of elements that
an array can holds. There is no predefined method to
obtain the length of an array.
 We can find the array length in Java by using the
array attribute length. We use this attribute with the
array name.
 The length property can be invoked by using the dot (.)
operator followed by the array name.

4/6/2024
63

 Processing Arrays
 When processing array elements, we often use
either for loop or for-each loop because all of the
elements in an array are of the same type and the size
of the array is known.

4/6/2024
64

 The for-each Loops


 For-each is another array traversing technique like for loop,
while loop, do-while loop introduced in Java5.
◼ It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable,
you declare a variable that is the same type as the base
type of the array, followed by a colon, which is then
followed by the array name.
◼ In the loop body, you can use the loop variable you created
rather than using an indexed array element.

4/6/2024
Exercise:
65

1. Write a Java program to sum values of an array.


Array Elements: {1,2,3,4,5}
The sum of the array is: 15
2. Write a Java program to calculate the average value
of array elements.
Array Elements: {1,2,3,4,5}
The average of the array is: 3.0
3. Write a Java program to find the maximum and
minimum value of an array.
Array Elements: {1,2,3,4,5}
The average of the array is: 3.0

4/6/2024
66

 Multidimensional arrays
 Multidimensional arrays with two dimensions are often
used to represent tables of values consisting of
information arranged in rows and columns.
◼ To identify a particular table element, we must specify two
indices. By convention, the first identifies the element’s row
and the second its column.
 Arrays that require two indices to identify a particular
element are called two-dimensional arrays.
(Multidimensional arrays can have more than two
dimensions.)
 In general, an array with m rows and n columns is
called an m-by-n array. 4/6/2024
67

 Example
 int [][] myArray = new int [3][4];
 int [][] myArray = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}};

4/6/2024
68

 Jagged Array [Multi dimensional Array]


 Itis an array of arrays such that member arrays can
be of different sizes, i.e., we can create a 2-D array
but with a variable number of columns in each row.
 These types of arrays are also known as Jagged
arrays.
 Example
 int [][] myArray = new int [3][];
◼ myArray[0]=new int[2];
◼ myArray[1]=new int[3];
◼ myArray[2]=new int[4];
 int [][] myArray = { {1,2}, {5,6,7}, {9,10,11,12}};
4/6/2024
69

 Passing Arrays to Methods


 Justas you can pass primitive type values to methods,
you can also pass arrays to methods.
 For example, the following method displays the
elements in an int array −

4/6/2024
70

 Returning an Array from a Method


A method may also return an array. For example, the
following method returns an array that is the reversal
of another array −
 Example

4/6/2024
71

 java.util.Arrays class: Built-in methods for


working with an array
 Ithelps you avoid reinventing the wheel by providing
static methods for common array manipulations.
 Before we can use the methods below, we need to
import the class, which we do easily by entering import
java.util.Arrays;
◼ Arrays.sort(datatyp [] a)
Sorts the specified array in ascending order, according to its
natural order.
◼ Arrays.toString(datatyp [] a)
Returns the contents of the specified array as a text string,
i.e. of data type String.
4/6/2024
72

 Printing an Array as String


 Single dimensional array
int myNewArray[]= new int []{1,2,3,4};
System.out.println(Arrays.toString(myNewArray));
 Multi dimensional array
int [][] mySecondArray=new int[2][4];
System.out.println(Arrays.deepToString(mySecondArray));

4/6/2024
73

 Common error when using array in Java

4/6/2024
String in Java
74

 String is a sequence of characters.


 Butin Java, string is an object that represents a
sequence of characters.
 The java.lang.String class is used to create a string
object.
 How to create a string object?
 There are two ways to create String object:
◼ By string literal
◼ By new keyword

4/6/2024
75

 String Literal
◼ Java String literal is created by using double quotes.
◼ For Example:
String s="welcome";
◼ Each time you create a string literal, the JVM checks the
"string constant pool" first.
◼ If the string already exists in the pool, a reference to the pooled
instance is returned.
◼ If the string doesn't exist in the pool, a new string instance is
created and placed in the pool.
◼ String s1="Welcome";
◼ String s2="Welcome";//It doesn't create a new instance

4/6/2024
76

 By new keyword
String s=new String("Welcome");
//creates two objects and one reference variable
◼ In such case, JVM will create a new string object in normal
(non-pool) heap memory, and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).

4/6/2024
77

 String constructors
 Class String provides constructors for initializing String
objects in a variety of ways.

4/6/2024
78

 Java String class method


 Length of string [length()]
◼ Returns string length
 charAt() method
◼ Returns char value for the particular index
 Comparing Strings
◼ String Method equals [equals()]
◼ Checks the equality of string with the given object.
◼ Comparing Strings with the == Operator
◼ When primitive-type values are compared with ==, the result is true
if both values are identical. When references are compared with
==, the result is true if both references refer to the same object in
memory.

4/6/2024
79

◼ String Method equalsIgnoreCase()


◼ Compares another string. It doesn't check case.
◼ String Method compareTo()
◼ Method compareTo returns 0 if the Strings are equal, a negative
number if the String that invokes compareTo is less than the String
that’s passed as an argument and a positive number if the String
that invokes compareTo is greater than the String that’s passed
as an argument.
 String Methods startsWith() and endsWith()
◼ startsWith() - determines whether each String in the array
starts with the specified characters
◼ endsWith() - determines whether each String in the array
ends with the specified characters .

4/6/2024
80

 Extracting Substrings from Strings


◼ String substring(int beginIndex)
◼ Returns substring for given begin index.
◼ String substring(int beginIndex, int endIndex)
◼ Returns substring for given begin index and end index.
 Concatenating Strings [concat()]
◼ Stringmethod concat() concatenates two String objects and
returns a new String object containing the characters from
both original Strings.

4/6/2024
Miscellaneous String Methods
81

Method Description
boolean contains(CharSequence s) returns true or false after matching the sequence
of char value.
String replace(char old, char new) replaces all occurrences of the specified char
value.
String toLowerCase() returns a string in lowercase.
String toUpperCase() returns a string in uppercase.
String trim() removes beginning and ending spaces of this
string.
char[] toCharArray() returns a char array containing a copy of the
string’s characters.

String[] split(String regex) returns a split string matching regex.

4/6/2024
Exercise:
82

1. Write a Java program to get the length of a given


string.
 Sample Output:
◼ The string length of 'example.com' is: 11
2. Write a Java program to convert all the
characters in a string to uppercase.
 Sample Output:
◼ Original String: Ethiopia
◼ String in uppercase: ETHIOPIA

4/6/2024
83

Questions?
4/6/2024
84

Thank You
4/6/2024

You might also like