Lecture 03 v2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Object-Oriented Programming

Lecture 3 – Java Objects and Classes

Ralph Tambala

MUST . CSIT

Lecture 3 1 / 24
Outline

1 Java Language
2 Hello World Program
3 Acces Modifiers
4 Declaring Classes
5 DeclaringAttributes
6 Declaring Methods
7 Declaring Objects
8 Accessing Instance Attributes and Methods
9 Constructors

Lecture 3 2 / 24
Java Language

Brief History of Java

Year Notable event/release


1995 Sun announces Java
1996 JDK 1.0
1997 JDK 1.1 RMI, AWT, Servlets
1998 Java 1.2 Reflection, Swing, Collections
2004 J2SE 1.5 (Java 5) Generics, enums
2014 Java SE 8 Lambdas
2017 Java SE 9
2018 Java SE 10, Java SE 11
2019 Java SE 12, Java SE 13
2020 Java SE 14, Java SE 15
2021 Java SE 16 (March), Java SE 17 (September)

Lecture 3 3 / 24
Java Language

Java Technology
JDK (Java Development Kit) – A software development kit used for
making applets and Java applications.
JRE (Java Runtime Environment) – A software layer for running Java
programs.
JVM (Java Virtual Machine) – A virtual machine that enables a
computer to run Java programs as well as programs written in other
languages that are also compiled to Java bytecode.

Lecture 3 4 / 24
Java Language

Features (1)
Simple –It is simple to learn and use. Java does not use pointers,
hence easy to write and debug programs. It also provides a simple
and clear approach to achieve a task using OOP concepts.
Pure object-oriented – Java Programs require the use of classes and
objects compulsorily.
Portable – Java compiler generates a set of instructions known as the
bytecode. Bytecode is executed by JVM.
Secure – Java programs are confined to JRE. They can access only
that part of the system which is required for program execution. Data
outside JRE cannot be accessed by Java programs, which makes it
secure.
Robust – Java performs exception handling that compels the
programmer to resolve mistakes during compile time. Memory
allocation and deallocation is automatic, and is done by means of
automatic garbage collection.
Lecture 3 5 / 24
Java Language

Features (2)

Scalable – Java is not limited to computers, and can also be extended


to embedded systems.
Platform independent – Java programs can be executed anywhere on
any system. It is platform independent in source form as well as
compiled binary form.
Multi-threaded – Java supports multithreading. Multithreading is
enabling multiple threads execute in a single Java Program
simultaneously.
Dynamic language – Java supports dynamic binding, or dynamic
linking.
Distributed – Can be used to create applications to communicate over
the network. It supports TCP/IP.

Lecture 3 6 / 24
Hello World Program

Hello World

1 /* *
2 * The HelloWorld class implements an application that
3 * simply prints " Hello World !" to standard output .
4 */
5
6 class HelloWorld
7 {
8 public static void main ( String [] args )
9 {
10 System . out . println ( " Hello World ! " ) ; // Display message
11 }
12 }
Listing 1: HelloWorld.java

Lecture 3 7 / 24
Hello World Program

Steps to Run Hello World Program

Follow the following steps to run Listing 1 – HelloWorld:


1 Write a program in notepad and save as HelloWorld.java
2 Open Command Prompt.
3 Navigate to the directory in which the HelloWorld.java file is saved.
4 Use the following command to compile the Java program.
javac HelloWorld.java
This will generate a HelloWorld.class file in the same folder.
5 Finally, use the following command to run the Java program:
java HelloWorld
The output should be Hello World!
NB: If the commands are not recognized, make sure you set Enviroment
Variables.

Lecture 3 8 / 24
Hello World Program

Breakdown of Hello World Program


Comments

Comments are ignored by the compiler but are useful to other


programmers. The Java programming language supports three kinds of
comments:
/* text */
◦ The compiler ignores everything from /* to */.
/** documentation */
◦ This indicates a documentation comment (doc comment, for short).
The compiler ignores this kind of comment, just like it ignores
comments that use /* and */. The javadoc tool uses doc comments
when preparing automatically generated documentation.
// text
◦ The compiler ignores everything from // to the end of the line.

Lecture 3 9 / 24
Hello World Program

Breakdown of Hello World Program


Class definition

A class in its simplest form can be defined as follows:


1 class HelloWorld
2 {
3 // class body
4 }
Listing 2: Class definition

The keyword class begins the class definition for a class named
HelloWorld.
The class body component contains declarations for the class’s
member variables, and declarations and implemenatations for the
class’s methods.

Lecture 3 10 / 24
Hello World Program

Breakdown of Hello World Program


The main method

In the Java programming language, every application must contain a main


method:
1 public static void main ( String [] args )
2 {
3 // statements
4 }
Listing 3: The main method

The modifiers public and static can be written in any order, but
the convention is to write public static.
The main method accepts a single argument: an array of elements of
type String. The argument can be given any name, but most
programmers choose “args” or “argv”.
.
Lecture 3 11 / 24
Hello World Program

Breakdown of Hello World Program


Statement

Finally, we take a look at the statement:


1 System . out . println ( " Hello World ! " ) ;
Listing 4: Statement

In short, this statement uses the System class from the core library to
print the "Hello World!" message to standard output.

Here’s a refined version:


System is a final class in java.lang package
out is a static member field of System class and is of type
PrintStream.
println is a method of PrintStream class. println prints the
argument passed to the standard console and a newline.

Lecture 3 12 / 24
Acces Modifiers

Acces Modifiers
Java has 4 access modifiers to set access levels for classes, attributes,
methods and constructors:
1 Default (No keyword) – If we do not provide any keyword explicitly,

the fields in an interface are implicitly public static final and the
methods are public by default.
2 private – Attributes, methods and constructors declared private

can only be accessed within the declared class itself. Class and
interfaces cannot be private.
3 public – Classes, attributes, methods and constructors declared

public can be accessed from any other class. The main method of
an application must be set to public.
4 protected – Attributes, methods and constructors declared

protected in a superclass can only be accessed by the subclasses in


other package or any class within the package of the protected
memmbers’ class. Classes and interfaces cannot be declared
protected.
Lecture 3 13 / 24
Declaring Classes

Declaring Classes
Classes are user-defined type. Class members describe the data
(attributes) and the behavior (methods).
Syntax:
<modifier>* class <class_name> {
<attribute_declaration>*
<constructor_declaration>*
<method_declaration>*
}
Example:
1 public class Counter {
2 private int value ; // attribute
3 public int getValue () { // method
4 return value ;
5 }
6 public Counter () {} // constructor
7 }
Lecture 3 14 / 24
DeclaringAttributes

Declaring/Initializing Attributes

Syntax:

// declaring attribute
<modifier>* <type> <attribute_name>;

// initializing attribute
<modifier>* <type> <attribute_name> = <initial_value>;

Example:
1 class Account {
2 private int accountNumber ; // declaration
3 public String accountName ; // declaration
4 private boolean status = false ; // initialization
5 }

Lecture 3 15 / 24
Declaring Methods

Declaring Methods
Syntax:
<modifier>* <return_type> <method_name>( <argument>* ) {
<statement>*
}
Example:
1 public class Counter {
2 public static final int MAX = 100;
3 private int value ;
4 public void inc () {
5 if ( value < MAX ) {
6 ++ value ;
7 }
8 }
9 public int getValue () {
10 return value ;
11 }
12 }
Lecture 3 16 / 24
Declaring Objects

Declaring Objects
An object is created from a class. The new keyword is used to create new
objects.

Syntax:
<class_name> <object_name> = new <class_name>();
Example:
1 public class Student {
2 public String name ;
3 public int year ;
4 public boolean active = true ;
5
6 public static main ( String [] argv ) {
7 Student st1 = new Student () ; // first object
8 Student st2 = new Student () ; // second object
9 }
10 }

Lecture 3 17 / 24
Accessing Instance Attributes and Methods

Accessing Instance Attributes and Methods (1)

Syntax:

// creating an object
<class_name> <object_name> = new <class_name>();

// accessing class attribute


<object_name>.<attribute_name>;

// accessing class method


<object_name>.<method_name>();

// assigning class attribute with public modifier


<object_name>.<attribute_name> = <value>;

Lecture 3 18 / 24
Accessing Instance Attributes and Methods

Accessing Instance Attributes and Methods (2)

Example:
1 public class Student {
2 public String name ;
3 public int year ;
4 private boolean active ;
5
6 public boolean setStatus ( boolean status ) {
7 active = status ;
8 }
9
10 public static main ( String [] argv ) {
11 Student st = new Student () ;
12 st . name = " Tiyamike " ; // assigning attr of object st
13 st . setStatus ( true ) ; // calling method of object st
14 }
15 }

Lecture 3 19 / 24
Constructors

Constructors

Constructor is a block of code that initializes the newly created object. A


constructor resembles an instance method in Java, but it is not a method
as it cannot have a return type. A class can have any number of
constructors.
Constructor has same name as the class. Example:
1 class Student { // class
2 Student () { // constructor
3 }
4 }

There are 3 types of constructors:


1. Default constructor
2. No-arg constructor
3. Parameterized constructor

Lecture 3 20 / 24
Constructors

Constructors
Default

If you do not implement any constructor in a class, Java compiler inserts a


default constructor into the code on your behalf. This constructor is
known as default constructor.

Example:
1 class Student {
2 String name ;
1 class Student {
3
2 String name ;
4 Student () { }
3 }
5 }
Listing 5: Original code Listing 6: Java inserts default
constructor

Lecture 3 21 / 24
Constructors

Constructors
No-arg

Constructor with no arguments is known as no-arg constructor. The


signature is same as default constructor, however, body can have any code
unlike default constructor where the body is empty.

Example:
1 class Student {
2 String name ;
3 Student () { // no arguments
4 this . name = " Mpanda Dzina " ; // some code
5 }
6 public static main ( String [] argv ) {
7 Student st = new Student () ;
8 System . out . println ( st . name )
9 }
10 }

this keyword, in this example, refers to the current object st.


Lecture 3 22 / 24
Constructors

Constructors
Parameterized

Parameterized constructor is a constructor with at least one


argument/parameter.

Example:
1 class Student {
2 String name ;
3 Student ( String fullName ) { // has 1 parameter
4 name = fullName ;
5 }
6 public static main ( String [] argv ) {
7 Student st = new Student ( " Alinafe Tambala " ) ; // ***
8 System . out . println ( st . name )
9 }
10 }

Lecture 3 23 / 24
Constructors

practice

Lecture 3 24 / 24

You might also like