0% found this document useful (0 votes)
23 views

Java Chapter 02 Gute Ma

Uploaded by

demissie ejo
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Chapter 02 Gute Ma

Uploaded by

demissie ejo
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Dambi Dollo University 2013

Department of Computer science

Object-Oriented
PROGRAMMING

Presented by: Gutema Bulcha


Chapter TWO

OBJECT AND CLASS


2.1 Java overview

 Java is an Object Oriented Programming language developed by Sun


Microsystems in the year 1991.
 Initially it was named as “Oak” by James Gosling
 In 1995, “Oak” is renamed to “Java” because the name “Oak” did not
survive legal registration.
 Java is guaranteed to be Write Once, Run Anywhere.

Java programming is:-  Object Oriented


 Platform Independent
 Simple
 Secure
 Robust
 High Performance
 Distributed
Object Oriented: In Java, everything is an Object. Java can
be easily extended since it is based on the Object model.
Platform Independent: Unlike many other programming
languages including C and C++, when Java is compiled, it is
not compiled into platform specific machine, rather into
platform independent byte code on.
Simple: : Java is designed to be easy to learn
Secure: With Java's secure feature it enables to develop virus-
free, tamper-free systems.
Robust: Java makes an effort to eliminate error prone
situations by emphasizing mainly on compile time error
checking and runtime checking.
High Performance: With the use of Just-In-Time compilers,
Java enables high-performance.
Distributed: Java applications can open and access remote
objects on Internet as easily as they can do in a local system.
2.2 Class and object
 The two most important concepts in object-oriented programming are
the class and the object.
1. Object
An object is an any real world entity which may represent place,
person, data item related to program.
An object has state and behavior.
Ex. A ‘light’ object has,
State: on/off
Behavior: switch
An object is a variable/instance of class.
An object is a run-time entity.
 An Object has two primary components:
state – properties of the object
behavior – operations the object can perform
For example, a Student object may consist of data such as
name, gender, birth date, home address, phone number, and
age and operations for assigning and changing these data
2. Class
 Is the template or blueprint that defines the states
and the behaviors common to all objects of a
certain kind.
 It is a collection of objects of similar type.
 Classes are user-defined data types & behave like
the built-in types of programming language.
In writing object-oriented programs we must first define
classes, and while the program is running, we use the
classes and objects from these classes to accomplish
tasks.
Class Declaration
class class name
{

Class Body
…}
2.3 Java Basic syntax

Let us now briefly look into what do class, object, methods,


and instance variables mean.
Object - Objects have states and behaviors.
object state behavior
dog breed, isHungry, eat, bark,sleep
age, color
light on/off switch
Class - A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type
supports.
Methods - A method is basically a behavior. A class can
contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of
instance variable object's state is created by the values
assigned to these instance variables.
First Java Program
Let us look at a simple code that will print the words Hello
World.
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
About Java programs, it is very important to keep in mind
the following points.
 Case Sensitivity - Java is case sensitive, which means
identifier Hello and hello would have different meaning
in Java.
 Class Names - For all class names the first letter should
be in Upper Case. If several words are used to form a
name of the class, each inner word's first letter should be
in Upper Case.
Example: class MyFirstJavaClass
Class Employee
 Method Names - All method names should start with a
Lower Case letter. If several words are used to form the name
of the method, then each inner word's first letter should be in
Upper Case.
Example: public void myMethodName()
Public void addNumber()
 Program File Name - Name of the program file should
exactly match the class name. When saving the file, you
should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name
(if the file name and the class name do not match, your
program will not compile).
 Example: Assume 'MyFirstJavaProgram' is the class
name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program
processing starts from the main() method which is a
mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for
classes, variables, and methods are called identifiers.
In Java, there are several points to remember about
identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a
to z), currency character ($) or an underscore (_).
 After the first character, identifiers can have any
combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value,
__1_value.
 Examples of illegal identifiers: 123abc
Java Modifiers
Like other languages, it is possible to modify classes,
methods, etc., by using modifiers. There are two
categories of modifiers:
Access Modifiers: default, public , protected,
private
Non-access Modifiers: final, abstract ..etc
Java Keywords
The following list shows the reserved words in Java.
abstract assert Boolean Break

byte case catch Char


class const continue Default
do double else Enum
extends final finally Float
for goto if Implements
import instanceof int Interface
long native new Package
private protected public Return
short static strictfp Super
switch synchronized this Throw
throws transient try Void
Comments in Java
Java supports single-line and multi-line comments very
similar to C and C++.
All characters available inside any comment are
ignored by Java compiler.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args){
// This is an example of single line
comment
/* This is also an example of single line
comment. */
System.out.println("Hello World");
}
}
What is variable?
Variables are the names you give to computer memory
locations which are used to store values in a computer
program.
For example, assume you want to store two values 10
and 20 in your program and at a later stage, you want to
use these two values.
Creating an object
As mentioned previously, a class provides the
blueprints for objects. So basically, an object is created
from a class. In Java, the new keyword is used to create
new objects
There are three steps when creating an object from a
class:
 Declaration: A variable declaration with a variable
name with an object type.
Instantiation: The 'new' keyword is used to create the
object.
 Initialization: The 'new' keyword is followed by a
call to a constructor. This call
initializes the new object.
Syntax for object creation:
classname objectname; //declares a variable to hold the
object reference
objectname = new classname( ); // Assigns the object
reference to the variable
Example:
Rectangle R1=new Rectangle();
Basic data type
Variables are nothing but reserved memory locations to
store values. This means that when you create a variable
you reserve some space in the memory. Based on the
data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved
memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters
in these variables.
There are two data types available in Java:
 Primitive Datatypes
 Reference/Object Datatypes
Primitive Datatypes
There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and
named by a keyword. Let us now look into the eight
primitive data types in detail.
Integer
This group includes byte, short, int, long.
byte:
 Byte data type is an 8-bit signed two's complement
integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte datatype is used to save space in large arrays,
mainly in place of integers, since a byte is four times
smaller than an integer
 Example: byte a = 100 , byte b = -50
short:
 Short datatype is a 16-bit signed two's complement
integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short datatype can also be used to save memory as byte
data type.
A short is 2 times smaller than an integer
 Default value is 0
 Example: short s = 10000, short r = -20000
int:
 Int datatype is a 32-bit signed two's complement integer
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for
integral values unless there is a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
long:
 Long datatype is a 64-bit signed two's complement
integer
 Minimum value is -9,223,372,036,854,775,808 (-2^63)
 Maximum value is 9,223,372,036,854,775,807
(inclusive) (2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
 Floating-Point Number
This group includes float, double
float:
 Float datatype is a single-precision 32-bit IEEE 754
floating point
 Float is mainly used to save memory in large arrays of
floating point numbers
 Default value is 0.0f
 Float datatype is never used for precise values such as
currency
 Example: float f1 = 234.5f
double:
 double datatype is a double-precision 64-bit IEEE
754 floating point
 This datatype is generally used as the default data
type for decimal values, generally the default choice
 Double datatype should never be used for precise
values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4
boolean:
 Boolean datatype represents one bit of information
 There are only two possible values: true and false
 This datatype is used for simple flags that track
true/false conditions
 Default value is false
 Example: Boolean one = true
char:
 char datatype is a single 16-bit Unicode character
 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char datatype is used to store any character
 Example: char letterA ='A'
Reference Datatypes

Reference variables are created using defined constructors


of the classes. They are used to access objects. These
variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy, etc
A reference variable can be used to refer any object of the
declared type or any compatible type.
 Example: Animal animal = new Animal(“dog");
Accessing class Members
To access members (fields and the methods) of an object
use the dot (.) operator together with the reference to an
object.
The general syntax is as follows:
objectname.variablename;
objectname.methodname(parameter-list);
Example:
R1.length=23;
R1.width=13;
System.out.println(“Area is “+ R1.rectArea());
R1.getData(34,15);
System.out.println(“Area is “+ R1.rectArea());
Complete Example
//instance method accessing instance variable
class Sample
{ int x = 10;
void display( )
{ x++;
System.out.println (" x value is : " + x);
}
}
class SDemo
{ public static void main(String args[])
{ Sample s1 = new Sample( );
System.out.print (“s1 Object Contains : “);
s1.display ();
Sample s2 = new Sample( );
System.out.print (“s2 Object Contains : “);
s2.display ();
}
}
Static Methods
 Static methods can read and act upon static variables.
 Static methods cannot read and act upon instance
variables.
 Static variable is a variable whose single copy is shared
by all the objects.
 Static methods are declared using keyword static.
 Static methods can be called using
objectname.methodname (or)
classname.methodname.
 From any object, if static variable is modified it affects all
the objects. Static variables are stored on method area.
Static Methods - Example
//static method accessing static variable
class Sample
{ static int x = 10;
static void display( )
{ x++;
System.out.println (" x value is = " + x);
}
}
class SDemo
{ public static void main(String args[])
{ System.out.print(“Calling static method using
Class name:“);
Sample.display ();
Sample s1 = new Sample ( );
System.out.print(“Calling static method using
Object name:“);
s1.display ();
}
}
Cont.
Example 2. Box volume
class Box {
double width, height, depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}}
 Although it is perfectly fine to create a class that contains
only data, it rarely happens. Most of the time you will use
methods to access the instance variables defined by the
class.
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo {
class Box { public static void main(String args[]) {
double width; Box mybox1 = new Box();
double height; Box mybox2 = new Box();
double depth; double vol;
// compute and return volume // initialize each box
double volume() { mybox1.setDim(10, 20, 15);
return width * height * depth; mybox2.setDim(3, 6, 9);
} // get volume of first box
// sets dimensions of box vol = mybox1.volume();
void setDim(double w, double h, double d) {System.out.println("Volume is " + vol);
width = w; // get volume of second box
height = h; vol = mybox2.volume();
depth = d; System.out.println("Volume is " +vol);
} }
} }
Returning a Value
 What if another part of your program wanted to know
the volume of a box, but not display its value?
 A better way to implement volume( ) is to have it
compute the volume of the box and return the
result to the caller.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}}
Constructors
It can be tedious to initialize all of the variables in a class each time an
instance is created. Even when you add convenience functions like
setDim( )…
It is possible to initialize objects they are created by:
Using the dot operator
The help of methods
But it would be simpler and more concise to initialize an object when
it is first created.
Java supports a special type of method, called a constructor, that
enables an object to initialize itself when it is created.
Constructors are special methods that are used to construct an
instance of a class.
A constructor initializes an object immediately upon creation. But
object creation only doesn’t call constructor rather it will be called
when the object is instantiated.
Call the constructor(s) preceding it with the new keyword.
Class name and constructor name should be the same.
That is, it has the same name as the class in which it resides
and is syntactically similar to a method.
Constructors have no return type (not even void), this is
because they return the instance of the class itself.
Constructors should be public.
Constructors can not be inherited.
They can be overloaded. Many constructors with the same
name can be defined.
Types of Constructors

1. Default constructor: is the type of constructor with out


any argument.
2. Parameterized Constructor: is a constructor with one or
more argument.
When an instance of an object is created then the instance
will call the constructor.
It will be the default constructor which will be called, if
there are no any parameterized constructor.
But if there is any parameterized constructor, then it will
be the parameterized constructor with the specified
parameter(s) which will be called
Default Constructor
 When you do not write a constructor in a class, it implicitly has a constructor
with no arguments and an empty body.
class A
{
// Variable declaration and initialization
// Method definition
System.out.println(“Welcome”);
}
 But we can also have a default constructor with no parameter(s) as follows:

class A
{
// public A()
// Method definition
System.out.println(“Welcome”);
}
class employee
Parameterized Constructors
{
private String Ename, empno;
private float salary;
employee(String eno, String name, float sal)
{
empno = eno;
Ename= name;
salary = sal;
}
public void print()
{
System.out.prinln(empno+”\t”+Ename+”\t”+sal);
}
}
public class demoEmp
{
public static void main(String args[])
{
Employee emp = new employee(“Au196/03”, “Jhon Micheal”, 2563.54);
}}
Cont…Example box public static void main(String
class Box { args[]) {
double width; // declare, allocate, and initialize
double height; Box objects
double depth; Box mybox1 = new Box(10, 20,
// This is the constructor for Box. 15);
Box(double w, double h, double Box mybox2 = new Box(3, 6, 9);
d) { double vol;
width = w; // get volume of first box
height = h; vol = mybox1.volume();
depth = d; System.out.println("Volume is "
} + vol);
// compute and return volume // get volume of second box
double volume() { vol = mybox2.volume();
return width * height * depth; System.out.println("Volume is "
} + vol);
} class BoxDemo7 { }
}
this Keyword
Sometimes a method will need to refer to the object that
invoked it. To allow this, Java defines the this keyword.
Instance can refer to itself with the keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
}
Recursion
 Recursion is the process of return result;
defining something in terms of }
itself. As it relates to Java }
programming, recursion is the class Recursion {
attribute that allows a method to public static void main(String args[]) {
call itself. Factorial f = new Factorial();
 A method that calls itself is said to
System.out.println("Factorial of 3 is " +
f.fact(3));
be recursive.
System.out.println("Factorial of 4 is " +
Example: factorial f.fact(4));
class Factorial { System.out.println("Factorial of 5 is " +
// this is a recursive function f.fact(5));
}
int fact(int n) {
}
int result;
if(n==1) return 1;
result = fact(n-1) * n;
Operators
Are symbols that take one or more arguments (operands) and
Operates on them to a produce a result.
 Are used to in programs to manipulate data and variables.
 They usually form a part of mathematical or logical
expressions.
Expressions can be combinations of variables, primitives and
operators that result in a value.
There are 8 different groups of
operators in Java:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operator
 Increment/Decrement
operators
 Conditional operators
 Bitwise operators
 Special operators

You might also like