Classes in Java
Overview
Teaching: 30 min
Exercises: 30 minQuestions
What are the principles of Object-Oriented Programming?
How do we create classes in Java?
Objectives
Explain the four principles of OOP.
Build an example Rectangle class.
JiP2.1-OOP-intro.pptx - slides download JiP2.2-OOP-classes.pptx - slides download
[access privacy] [return type] [identifier] (type arguments) { ... } public boolean odd(int input){ ... }
Define a new method called oddSum that, given an array of ints, e.g. arr, as an argument returns the sum of the odd numbers using the odd method. Implement a third method in OddEven that returns the sum of the even numbers, invoking the oddSum method in the process. Test your function from a Main class extracting and printing the odd and even numbers from arr array. Remember a for loop iterates through each element in a list and variables for cumulative updates must be created before the loop.
int[] arr = [1, 42, -3, 2, 39]
for (int num : arr ) {
//this for each loop iterates through each item in an array
//do something with each_number
}
Solution OddEven.java Solution Main.java - see exercise 5
Write another method, firstDigit, that returns the first digit of its integer argument. Thus, DigitExtraction.FirstDigit(657) should return 6. Make sure that your program works for negative numbers too.
You may find the remainder operator or modulo operator useful. This gives the remainder when the left hand operand is divided by the right hand operand as below. Create a DigitExtract object in Main and test your functions there as well.
>>> 10 % 2
0
>>>11 % 2
1
>>> -10 % 3
-1
Solution DigitsExtraction.java
Solution Main.java see exercise 2
Key Points
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