Week 2
Declaring a class and creating
objects
Dr. Nehad Ramaha,
Computer Engineering Department
Karabük Universities 1
The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes.
In Java, every application begins with a class name, and that class must
match the filename.
Let's create our first Java file, called Main.java, which can be done in any
text editor (like Notepad).
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Save the code in Notepad as "Main.java".
The main() method is required and you will see it in
every Java program:
2
Open Command Prompt
(cmd.exe), navigate to the
directory where you saved your
file, and type:
◦ javac Main.java
This will compile your code. If
there are no errors in the code,
the command prompt will take
you to the next line. Now, to
run the file type:
◦ java Main
The JVM takes the byte code and generates
machine code.
3
Java Standard Edition (SE) contains the capabilities needed
to develop desktop and server applications.
The Java Enterprise Edition (Java EE) is geared toward
developing large-scale, distributed networking
applications and web-based applications.
Java Micro Edition (Java ME) a subset of Java SE. geared
toward developing applications for resource-constrained
embedded devices, such as:
◦ Smart watches
◦ MP3 players
◦ television set-top boxes
◦ smart meters (for monitoring electric energy usage)
◦ and more.
4
Objects (comes from classes) are reusable.
◦ Date, time, audio, video, automobile, people objects,
etc.
◦ Almost any noun can be represented as an object in
terms of
attributes (e.g., name, color and size) and
behaviors (e.g., calculating, moving and communicating).
Object-oriented design approach is much more
productive than with earlier popular techniques like
“structured programming”
Object-oriented programs are often easier to
understand, correct and modify.
5
Class − A class is a blueprint or
template or set of instructions to
build a specific type of object
Object- An object is a component
that contains attributes and
behaviors needed to make a
certain type of data useful.
Instance- An instance is a specific
object built from a specific class
6
Objects have
attributes (e.g., name, color and size) and (variables)
behaviors (e.g., calculating, moving and communicating). (methods)
A car has attributes
◦ Color, its number of doors, the amount of gas in its
tank, its current speed and its record of total miles
driven (i.e., its odometer reading).
◦ The car’s attributes are represented as part of its design
in its engineering diagrams.
Every car maintains its own attributes.
methods are used to perform some tasks of the
objects.
7
Just as someone has to build a car from its
engineering drawings before you can actually
drive a car, you must build an object of a
class before a program can perform the tasks
that the class’s methods define.
An object is then referred to as an instance of
its class.
8
A class is a blueprint from which individual objects are created.
public class Dog {
String breed;
variables
int age;
String color; attributes public class JavaApplication1 {
public static void main(String[] args)
{
void bark() {}
methods
Dog dog = new Dog();
void hunger() {}
void sleep() {} behaviors dog.bark();
}
} }
Object: An instance of Dog class Method call
9
Another Example: Car class Behaviours
Attributes
StartEngine
Model
Color Drive
Year Stop
Price
This Car class can be reused many times to build many cars, you can reuse a class
many times to build many objects.
Reuse of existing classes when building new classes and programs saves time and
effort.
10
Need for OOP
11
POP OOP
Main focus is on "how Main focus is on 'data
to get the task done" security'. Hence, only
i.e. on the procedure
or structure of a objects are permitted to
program access the entities of a
Large program is class.
divided into Entire program is divided
functions(methods) into objects.
C, VB, FORTRAN, C++, JAVA, C#,
Pascal Objective-C, phyton
12
int myNum = 5; // Integer (whole number)
double myNum = 19.99d; // double
float myFloatNum = 5.99f; // Floating point number
Primitive Data Types
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
13
FORMAT
SPECIFIE CONVERSION APPLIED
Integer formatted output R
%% Inserts a % sign
System.out.printf("Sum is %x %X Integer hexadecimal
%d%n", sum); %t %T Dime and Date
%s %S String
◦ Format specifier %d is a %n Inserts a newline character
placeholder for an int value %o Octal integer
%f Decimal floating-point
◦ The letter d stands for “decimal %e %E Scientific notation
Causes Formatter to use either %f
integer.” %g
or %e, whichever is shorter
%h %H Hash code of the argument
%d Decimal integer
%c Character
%b %B Boolean
%a %A Floating-point hexadecimal
14
Conditional statements
◦ If-else
◦ Switch-case
15
Loops
◦ For
◦ While
◦ Do-while
◦ For-Each Loop(with arrays)
Arrays
◦ Int[], float[], char[]…
16
Task: computing average score for students.
◦ We put students name, midterm and final exam
◦ Create a method to compute average score of a student.
float CalculateScore();
◦ Create another method to show student all info
void ShowStudentInfoAndScore();
Let's move to IDE
17
There is no need for OOP concepts at all. Almost all the software in
the world can be achieved using procedural (POP).
But OOP allows the programmer to think in terms of objects and
classes that makes it
◦ much easier to understand the code
◦ easy to code and modify it
◦ Reuse and existing code
◦ Much easier to hide data.
It makes software a set of interacting Objects.
18
Task: Same task
◦ We first create a Student class
put students name, midterm and final exam
◦ Create a student object from the class
float CalculateScore();
using student object
◦ Create a method to show all info
void ShowStudentInfoAndScore()
Let's move to IDE
19
◦ Every Java program consists of at least
one class that you define.
public class Dog { ◦ class keyword introduces a class
declaration and is immediately
String breed; followed by the class name.
int age; ◦ A public class must be placed in a
String color; file that has a filename of the form
void bark() {…} ClassName.java,
so class Dog is stored in the file
void hunger() {…} Dog.java.
void sleep() {…} ◦ A left brace, {, begins the body of every
class declaration.
}
◦ A corresponding right brace, }, must
end each class declaration.
20
An object must be declared with a name and a type
before they can be used.
Declaration statement
Scanner input = new Scanner(System.in);
You need to import this:
import java.util.Scanner;
Scanner Class
◦ Enables a program to read data for use in a program.
◦ Data can come from many sources, such as the user at the keyboard
or a file on disk.
21
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter first number: ");
int numberOne = input.nextInt();
System.out.println("Please enter second number: ");
int numberTwo = input.nextInt();
int result = numberOne + numberTwo;
System.out.printf(“ the result is %d %n“, result);
}
22
Methods can either return something or return void. If a method
returns something, then its name should explain what it returns,
for example:
•void get() BAD!
•boolean isValid(String name); GOOD!
•String content(); GOOD!
•int ageOf(File file); GOOD!
23
If it returns void, then its name should explain what it does. For
example:
Method Names
• void saveToLocation(File file);
• void process(Work work);
• void append(File file, String line);
•Variable Names
•Eg: name, age. mobileNumber
24
25
Create an Employee class includes
◦ Attributes
name (string)
socialSecurityNumber (int)
Wage (float)
workingHours (int)
◦ Behaviours
displayInfo()
Print name with socialSecurityNumber;
displaySalary()
Print salary (= wage * workingHours)
Create an employee object and initialize attributes.
Call displayInfo() and displaySalary() methods for employee
object.
Create another employee, and this time get attributes from the
keyboard
26