[go: up one dir, main page]

0% found this document useful (0 votes)
38 views25 pages

Class 3 - 27 February To 03 March 2023

Uploaded by

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

Class 3 - 27 February To 03 March 2023

Uploaded by

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

Object-

Oriented
Orogramming
(OOP): JAVA
CMPG 211
Week 2
27 February 2023 to 03 March 2023

Lecturer: Dr V Malele
Office: G15
Expectations

• After engaging with the materials and activities in this study unit you
should be able to:
• Understand difference between primitive and non-primitive data types
• Use Data Types in BlueJ
• Use the Java I/O package
• Understand the use of Java Keywords
• Oracle Document

• https://www.oracle.com/jav
a/technologies/downloads/
• https://docs.oracle.com/jav
ase/8/docs/technotes/guide
s/desc_jdk_structure.html
Variables
Java Variables
• Instance Variables (Non-Static Fields)
→Technically speaking, objects store their individual states in "non-static fields", that is,
fields declared without the static keyword.
→Non-static fields are also known as instance variables because their values are unique
to each instance of a class (to each object, in other words); the currentSpeed of one
bicycle is independent from the currentSpeed of another.
• Class Variables (Static Fields)
→A class variable is any field declared with the static modifier; this tells the compiler
that there is exactly one copy of this variable in existence, regardless of how many
times the class has been instantiated.
→A field defining the number of gears for a particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all instances.
→The code static int numGears = 6; would create such a static field.
→Additionally, the keyword final could be added to indicate that the number of gears
will never change.
Java Variables
• Local Variables
→ Similar to how an object stores its state in fields, a method will often store its
temporary state in local variables.
→ local variables are only visible to the methods in which they are declared; they are not
accessible from the rest of the class.
→ The syntax for declaring a local variable is similar to declaring a field (for example, int
count = 0;).
→ There is no special keyword designating a variable as local; that determination comes
entirely from the location in which the variable is declared — which is between the
opening and closing braces of a method.
• Parameters
• Recall that the signature for the main method of examples so far is:
public static void main(String[] args).
• Here, the args variable is the parameter to this method.
• The important thing to remember is that parameters are always classified as "variables"
not "fields".
Declaring a Variable
• In Java, the type of variable is checked at compile time.
• This is known as static typing.
• It has the advantage of catching the errors at compile time rather than at execution time.
• Variables must be declared with the appropriate data type or the program will not
compile.
• To syntax for declare a variable in Java:
(The data type) (The variable name) = (The value)
NB: Without brackets
• There are several kinds of variables:
• Member variables in a class—these are called fields.
• Variables in a method or block of code—these are called local variables.
• Variables in method declarations—these are called parameters
DIY: Variable Declaration
• Numbers and Texts
• In programming, we can directly use some fixed
values in our program. These fixed values are
called literals.
• Let's take a look at commonly used literals in Java.
1. Integers (int)
Integers are numbers without decimal parts. For
example, 5, -11, 0, 12, etc. For now, let's refer to integers
as simply int.
2. Floating-point Numbers (double)
Floating-point numbers contain decimal parts. For
example, 2.5, 6.76, 0.0, -9.45, etc. For now, let's refer to
floating-point numbers as double.
3. String (text)
In Java, texts wrapped inside double quotation marks are
called Strings.
DIY: Variable Declaration
System.out.println();
import java.io.*; System.out.prin
tln(num);
class PrintLN { System.out.prin
public static void tln(ch);
main(String[] args) System.out.prin
{ tln(str);
// Declaring System.out.prin
different datatypes tln(d);
int num = 10; System.out.prin
char ch = 'G'; tln(f);
String str = System.out.prin
“Zekethe"; tln(bool);
double d = 10.2; System.out.prin
float f = 13.5f; tln("Hello");
boolean bool = true; }
}
• See pages 573 to 575 of
Data Types

• In Programming, Data types define


the type of data that is to be stored in
a variable.
• Each variable has a property known as
its data type which determines what
kind of data can be stored in that
variable.
• In Java programming language, there
are two categories of data types:
• Primitive – these are built-in data types.
• Non-Primitive/reference data types –
these are user-defined data types
(except for String class)
Difference Between Primitive And Non-Primitive Data
Types In Java

Primitive data Non-Primitive data types


pre-defined in the system user-defined and programmers can easily
whereas create and modify them (except String class).
, variables can store only one we can store multiple values of either the
value at a time whereas, same data type or different data types in one
variable.
variables, or the data is stored a stack holds a reference to the object on heap
on a stack whereas memory. This object is the data whose
memory location is given as a reference to the
variable.
types start with the lower-case need to start with an upper-case initial letter
letter
int, long, char, byte, short, Array, Class, String, Interface.
boolean, etc.
Non-Primitive Data Type
• Non-Primitive are also called Reference data types also known as object data types,
• these are user-defined data types (except for String class).
• they can be easily created or modified by the users.
• they are references to a specific object.
• they can be used to store multiple values and invoke methods to perform certain operations.
• Different types of non-primitive data types exist in Java
• Annotations - allow metadata to be associated with elements of a program
• Arrays - store elements of the same type
• Classes - provide a template for object creation
• Enumeration - stores a fixed set of constants
• Interfaces - store a template for a class
• String
Classes
• Class is a user-defined data type that is used to create objects. A class contains a set of
properties and methods that are common and exhibited by all the objects of the class.
• All Classes in Java are non-primitive data types. Other examples of non-primitive data
types are Arrays and String
• There are various components of a class while its declaration:
• Access Modifier: A class can be declared as public by using the public keyword or can even
has default access where there is no need to include any access modifier.
• Class Name: The class name should have an initial letter in the capital according to the
naming conventions used. It is used for class identification and object creation.
• Superclass: It is not always necessary to have a parent class obviously, but if a class needs
to extend and inherit the properties of its parent class, the name of the parent class can be
written preceded by the keyword extends.
• Interfaces: A class can implement any number of interfaces where a list of interfaces is
included preceded by the keyword implements.
• Body and Members: The body of a class is surrounded by curly braces { } and it contains
data members and methods inside it.
DIY: Class
• Please type open BlueJ and
create the attached Class.
• Does it compile and give an
output? If not why?
DIY: Class

• Note:
• Every class should be called or
invoked from the Main Class for it
to give output.
• Upon creating an object of class
Demo, we have invoked two
functions with some parameters to
perform addition and subtraction
and the result will be then
displayed.
Strings
• Strings in Java are designed in such a way that they can hold a • DYI Example
sequence of characters in a single variable, unlike character public class Main {
arrays where there are separate char entities. public static void main(String[] args)
• There is no need to end strings in Java with the null character {
which is compulsory in the case of C/C++. String myStr1 = "Vusi";
String myStr2 = "Malele";
• Syntax for declaration of String:
String <string_variable_name> = “<sequence_of_characters>”; System.out.println(myStr1.compareT
Or oIgnoreCase(myStr2));

String <string_variable_name> = new String(“<sequence_of_characters>”); System.out.println(myStr1.concat(my


• The String class has a set of built-in methods that you can use Str2));
on strings. }
• See the list of String built-in Method }
DIY: Strings
• In this Java example code, we have declared two
strings : str1 and str2 using the non-primitive data
type String and initialized them with some values.
• Then show the output. Do you see the concatenation of
space in between?

• String Declaration using new Operator


• In this example, we have used an alternative
method of declaring the string str1 using the
new operator where the sequence of
characters is passed as a single parameter to
the new String() constructor and a reference
to the String object is stored in str1.
Array
• Arrays are non-primitive data types in Java that are used to store elements of the same data type in a
contiguous manner.
• They are not pre-defined and users have to declare and initialize arrays by themselves.
• Arrays have a unique reference name by which all their elements are accessed.
• Elements are stored in an indexed manner where the index starts from 0.
• Key points to remember about Arrays in Java:
• In Java, all arrays are dynamically allocated and their size can be declared by the programmer dynamically at run
time. This means memory space is allocated to Java arrays at run time rather than compile time.
• The size of an array must be specified by an integer value and not long or short.
• Syntax Declaration:
// Declaration of array
<data_type>[] <array_name> = new <data_type>[size];
// Declaration and Initialization of array at the same time
<data_type> <array_name> [] = {array_item_values};
• Usage:
int[] arr = new int[5]; int arr[] = {1,2,3,4,5}; // Declaration & Initialization as well
DIY: Arrays
• import java.util.*;
• In the example, we have declared and initialized arr1 with elements
1,2,3,4,5 and for arr2 of size 5, the user will input the elements. After
that, we print the values of elements of both the arrays as output
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in); // input the elements
int arr1[] = { 1, 2, 3, 4, 5 }; // Declaration & Initialization
int[] arr2 = new int[5]; // Array of size 5 declared
for (int i = 0; i < 5; i++)
{
arr2[i] = scn.nextInt();
}
scn.close();
System.out.print("Array arr1 elements: ");
for (int i = 0; i < 5; i++) {
System.out.print(arr1[i] + " ");
}
System.out.println();
System.out.print("Array arr2 elements: ");
for (int i = 0; i < 5; i++) {
System.out.print(arr2[i] + " ");
}
}
}
Interface
• Interface in Java is a tool to achieve abstraction.
• Interface can contain non-implemented methods (without the method body)
also known as abstract methods. This is the main difference between a class
and an interface.
• Interfaces in Java may contain:
• Abstract methods
• Default and static methods (since Java 8)
• Private methods (since Java 9)
• There are some key points to remember about interfaces in Java:
• If a class implements an interface, then it must also implement all the abstract
methods of that interface otherwise we need to declare that class as an abstract class.
• Interface specifies a set of methods that the class has to implement. In short, the
interface is a blueprint of the class.
DIY: Interface
• In this Java example code, we have
implemented an interface consisting of
two abstract methods declarations:
• void mult() and
• void div() without their bodies.
• Now, they need to be implemented by
the class Solve where we will
implement both the methods.
• Then we have made an object obj of
Solve class and using this, we will
invoke mult() and div() methods for
multiplication and division operations.
• At the end, the result after
mathematical operations will be
displayed as output.
The below Individual Task 1:
(No longer submitted)
However, if you have done it, please submit
for improving your marks.
[10]

Submit your answers to:


cmpg211submissions@gmail.com
Submission date: 2 March 2023 open ended
Individual Task 1
1. State the difference between high level and low-level programming
languages. Give four examples of the programming languages (i.e. two per
language level). Please do not include Java.
2. Compare OOP Languages: Java, Python, C#, C++, JavaScript, PHP, Ruby, Dart,
Perl, Swift, Scala, Objective. Use the table below as format (it should have 12
columns showing OOP lang).
C# C++ Python
Java, PhP
Class declarations
Method declarations
Constructors and destructors
Object declarations
Accessing fields of objects
Thank
You

You might also like