You are on page 1of 85

1

MORE ON OOP CONCEPTS

11/18/2021 OOP- CH-2- More on OOP Concepts


Contents
1. Overview
2. Input/output Operation
3. Class declaration and Objects instantiation
4. Static and Instance members
5. Methods and their components
6. Constructors (Default, parameterized and Overloaded)
7. Access modifiers
8. Accessors and Mutators
9. Array ad String
11/18/2021
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
11/18/2021
Input/ Output Operation
4

 Output Operation
 System.out.println();
 Input Operation
 Import scanner package
 import java.util.Scanner;
 Create scanner object
 Scanner reader=new Scanner(System.in)
 Read the value
 int num1=reader.nextInt();

11/18/2021
Class declaration and Objects instantiation
5

 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:
11/18/2021
6

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

11/18/2021
7

 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. 
11/18/2021
8

 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();

11/18/2021
Instance and Static members
9

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

11/18/2021
10

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

11/18/2021
11

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

11/18/2021
12

 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
11/18/2021
13

 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

11/18/2021
Instance and Static Variables
14

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

11/18/2021
15

 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);

11/18/2021
16

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

11/18/2021
17

 Example:
 Class_name.cal=10;
 Class_name.min=2;
 Class_name.display(4);

11/18/2021
Methods and their components
18

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

11/18/2021
19

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

11/18/2021
20

 Example

11/18/2021
21

 Method Calling
 For using 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.

11/18/2021
22

 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.
 PassingParameters by Value means calling a method with a
parameter. Through this, the argument value is passed to the
parameter.

11/18/2021
23

 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

11/18/2021
24

11/18/2021
Constructor
25

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

11/18/2021
26

 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() { }
}

11/18/2021
27

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

11/18/2021
28

 Example

11/18/2021
29

 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

11/18/2021
30

 Example

11/18/2021
Exercise 1:
31

 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.
11/18/2021
Exercise 2:
32

 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

11/18/2021
Exercise 3:
33

 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 11/18/2021
Exercise 4:
34

 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

11/18/2021
Exercise 5:
35

 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 11/18/2021
Exercise 6:
36

 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

11/18/2021
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
11/18/2021
Access Modifiers
38

 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

11/18/2021
39

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

11/18/2021
Example
40

11/18/2021
41 11/18/2021
42

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

11/18/2021
Example
43

11/18/2021
44

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

11/18/2021
45 11/18/2021
46

 Public access modifier


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

11/18/2021
47 11/18/2021
48 11/18/2021
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
11/18/2021
Accessors and Mutators
50

 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.
 If we have declared the variables as private then they
would not be accessible by all so we need to use getter
and setter methods.

11/18/2021
51

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

11/18/2021
52

 Example

11/18/2021
53

 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.
11/18/2021
54

 Example

11/18/2021
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
11/18/2021
Array in Java
56

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

11/18/2021
57

 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[];
11/18/2021
58

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

11/18/2021
59

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

11/18/2021
60

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

11/18/2021
61

11/18/2021
62

 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.
11/18/2021
63

 Array Length
 In Java, 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. 

11/18/2021
64

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

11/18/2021
65

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

11/18/2021
Exercise:
66

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
11/18/2021
67

 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. 11/18/2021
68

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

11/18/2021
69

 Jagged Array [Multi dimensional Array]


 It is 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}};
11/18/2021
70

 Passing Arrays to Methods


 Just as 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 −

11/18/2021
71

 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

11/18/2021
72

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


working with an array
 It helps 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. 11/18/2021
73

 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));

11/18/2021
74

 Common error when using array in Java

11/18/2021
String in Java
75

 String is a sequence of characters.


 But in 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

11/18/2021
76

 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

11/18/2021
77

 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).

11/18/2021
78

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

11/18/2021
79

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

11/18/2021
80

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

11/18/2021
81

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

11/18/2021
Miscellaneous String Methods
82

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.

11/18/2021
Exercise:
83

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

11/18/2021
84

Questions?
11/18/2021
85

Thank You
11/18/2021

You might also like