OOP Chapter 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51
At a glance
Powered by AI
The key takeaways are that objects have state defined by properties and behavior defined by methods. Classes define objects of the same type and provide constructors to initialize objects.

An object has a unique identity, state defined by properties, and behavior defined by methods.

A class defines the common characteristics of objects of the same type, while an object is an instance of a class - an object is a runtime entity with state and behavior according to its class.

Object-Oriented Programming

[CoEg2182]

Chapter Three:
Objects and Classes
Object
• Object-oriented programming (OOP) involves programming using
objects.
• An object represents an entity in the real world that can be
distinctly identified. For example, a student, a desk, a circle, a
button, and even a loan can all be viewed as objects.
• An object has a unique identity, state, and behaviors.
• The state of an object consists of a set of data fields (also known as
properties) with their current values.
• The behavior of an object is defined by a set of methods.
Objects
data field 1 radius = 5 Data field, State
Properties

... State
(Properties)

data field m findArea() Method,


Behavior
method 1

... Behavior

method n

(A) A generic object (B) An example of circle object

An object has both a state and behavior. The state defines the
object, and the behavior defines what the object does.
3
Classes
• Classes are constructs that define objects of the same
type.
• A Java class uses variables to define data fields and
methods to define behaviors.
• Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct
objects from the class.
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double findArea() { Method
return radius * radius * 3.14159;
}
}
Constructors
• Constructors are a special kind of methods that are invoked
to construct objects.

Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}
Constructors, cont.
• A constructor with no parameters is referred to as a no-
arg constructor.
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• Constructors are invoked using the new operator when an
object is created. Constructors play the role of initializing
objects.
Creating Objects Using Constructors
new ClassName();

• Example:
new Circle();

new Circle(5.0);
Default Constructor
• A class may be declared without constructors. In this case,
a no-arg constructor with an empty body is implicitly
declared in the class. This constructor, called a default
constructor, is provided automatically only if no
constructors are explicitly declared in the class.
Declaring Object Reference Variables
• To reference an object, assign the object to a reference variable.
• To declare a reference variable, use the syntax:
ClassName objectRefVar;
• Example:
Circle myCircle;
Declaring/Creating Objects in a Single Step
ClassName objectRefVar = new ClassName();

Create an object
• Example:
Assign object reference

Circle myCircle = new Circle();


Accessing Objects
• Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

• Invoking the object’s method:


objectRefVar.methodName(arguments)
e.g., myCircle.findArea()
Example program: TestCircle.java
public class TestCircle
{
public static void main (String args [ ] )
{
Circle circleOne = new Circle();
System.out.println(“This circle’s radius is ” + circleOne .radius);
System.out.println(“The area is ” + circleOne.findArea());
}
}
Explanation:
• This program creates a Circle object (refer to Circle class)
and displays its radius and area.
• Circle.java and TestCircle.java are different files. We
compile both files but only run TestCircle.
Example program: TestCircle2.java
public class TestCircle2{
public static void main (String args [ ] )
{
Circle circleOne = new Circle();
//new object and data
Circle circleTwo = new Circle(5.0);
System.out.println(“The area of circleOne is ” + circleOne.findArea( ));
System.out.println(“This circle’s radius is ” + circleOne .radius);
System.out.println(“The area of circleTwo is ” + circleTwo.findArea( ));
System.out.println(“This circle’s radius is ” + circleTwo .radius);
}
}//close TestCircle2
……..
Continued
……
class Circle {
double radius = 1.0;
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
double findArea() {
return radius * radius * 3.14159;
}
}//close Circle
Explanation:
• This program creates a Circle object (refer to Circle class) and
displays its radius and area.
• Circle.java and TestCircle.java are different files. We compile
both files but only run TestCircle.
• You can put two classes into one file, but only one class can be
public class.
• Public class must have the same name as the file name (class
with main method).
• This program is same as Previous Program (TestCircle.java)
but with new object and new data - circleTwo
The this keyword
• Java this keyword is used to invoke any method or variable
of current class.
• The syntax of method is: -
this.methodname( );

• The syntax of variable is: -


this.variablename = 7;
• If you want to invoke another constructor of current class
inside constructor you can use this statement as follows:
this(4, 5);
• The above statement will invoke the current class
constructor that takes two int arguments.
• Call to current class constructor with this would be the
first statement in the constructor.
// Account.java
// Account class that contains a name instance variable
// and methods to set and get its value.
public class Account
{
private String name; // instance variable
// method to set the name in the object
public void setName(String name)
{
this.name = name; // store the name
}
// method to retrieve the name from the object
public String getName()
{
return name; // return value of name to caller
}
} // end class Account
Class Variables (static variables)
• The runtime system allocates class variables once per class
regardless of the number of instances created of that class.

• The system allocates memory for class variables the first time
it encounters the class at class load time.

• All instances share the same copy of the class variables.

• You can access class variables through an instance or through


the class itself.
To declare a class variable follow the following syntax.

static Type variable;


e.g.
static int a;
static double d;

If any object change the value of class variable, the


change will effect the values of all the variables.
Because the class variable belongs to the class rather
than any specific variable, it can be accessed using the
class name such as: -

ClassName.variableName;

Suppose you have class called Car and class variable


called gears than you can access that variable like this: -

Car.gears;
Class vs. Instance Variables
Class variable Instance variable
Class variable is declared by using Instance variable is declared
static keyword. without static keyword.

int a = 4;
static int a = 4;
All objects share the single copy of All objects have their own copy of
static variable. instance variable.
Static variable does not depend on Instance variable depends on the
the single object because it belongs object for which it is available.
to a class.

Static variable can be accessed Instance variable cannot be


without creating an object, by using accessed without creating an
class name. object.

ClassName.variable
ObjectName.variable
Class Methods(static methods)
• The class (static) methods is not referenced through a
particular instance of a class but through the class itself.

• You don’t have to create an object of the class to invoke a


static method.
Static Method Syntax
static Returntype methodname (parameters)
{
statement 1;
statement 2;
…..
}
example

static void display(int a, int b)


{
System.out.println(a+b);
}
Static vs. Instance Methods

Static Method Instance Method


Static methods are declared by instance methods are declared
using static keyword. without static keyword.

All objects share the single copy of All objects have their own copy of
static method. instance method.
Static method does not depend on Instance method depends on the
the single object because it belongs object for which it is available.
to a class.

Static method can be invoked Instance method cannot be invoked


without creating an object, by using without creating an object.
class name.

ClassName.method( ); ObjectName.method( );
Static methods cannot call non- Non-static methods can call static
static methods. methods.

Static methods cannot access not- Non-static methods can access


static variables. static variables.

Static methods cannot refer to this Instance methods can refer to this
or super. and super.
Get and Set methods
• We were able to create objects of the class Account and initialize the variables
of the object using the constructor. But after that, we can no longer change the
values the variables hold. The following statement would result in an error
since the variables were declared to be private(private String name;).
myAccount.name=“Abebe”
• The solution lies in providing public methods through which new values can be
assigned to these variables and the values they hold can be accessed. These
are commonly known as get and set methods.
• Get methods provide access to the value a variable holds while set methods
assign values to the variables of the objects.
Set methods
• In order to set a variable to a new value, the method needs arguments similar
to how the parameterized constructors required details such as name,…. These
required arguments are specified in the method header within the parentheses
by specifying the variable name and a data type for that variable name.
• Example:- A set method for name looks as shown below:
public void setName ( String n ) {
name = n;
}
• It is a convention to name the setter methods starting with the word 'set'
followed by the variable name that is going to be set.
• If we wish to set the name for the first Account object a1 which we have
created, we use the following statement:
a1.setName(“Abebe");
Get methods
• Now, we shall provide a get method for the variable name. As we have earlier
said, methods are capable of returning values. These values can be of any data
type. Here, we will be returning a String. The data type that is going to be
returned in specified in the method header instead of the word void. We have
used the word void till now to indicate that a method does not return any value.
• Example: The get method for name would be the following:
public String getName() {
return name;
}
• In the following statements, the value returned by getName is stored in the
variable aName and displayed.
String aName = a2.getName();
System.out.println ("Name of a1: "+ a2.getName() );
Access Modifiers
• Access modifiers define various levels of access between
class members and the outside world (other objects).
• They allow us to define the encapsulation characteristics of
an object.
• There are four access modifiers in java:
1. Private
2. Protected
3. Public
4. default.
private
• The private access modifier is the most restrictive; it specifies that
class members are accessible only by the class in which they are
defined. This means that no other class has access to private class
members, even subclasses.
private int a = 4;

private void show ( )


{
}
Car Bus Pizza Burger
private int a;

Package 1 Package 2

private variable a is only accessible in Car class.


protected
• This modifier specifies that class members are accessible
only to methods in that class, the classes inside the
package and subclasses of that class outside the package.
protected int a = 4;

protected void show ( )


{
}
Car Bus Pizza Burger
Protected int a;

Package 1 Package 2

protected variable a is accessible inside Car class and inside child


class which can be in same package or different package.
public
• The public access modifier specifies that class variables and
methods are accessible to anyone, both inside and outside the class.
This means that public class members have global visibility and can
be accessed by any other object.
public int a = 4;

public void show ( )


{
}
Car Bus Pizza Burger
public int a;

Package 1 Package 2

public variable a is accessible from all 4 classes in any package.


Default Access Modifier
• The default (package) access modifier specifies that only
classes in the same package can have access to a class's
variables and methods.

• There is no actual keyword for declaring the default access


modifier.

• it is applied by default in the absence of any access


modifier.
Car Bus Pizza Burger
int a;

Package 1 Package 2

Int variable a is accessible only inside Package 1.


Packages
• A package is a collection of related classes and
interfaces.
• Packages provide following benefits:
– Classes are easier to find and use
– No naming conflictions
– Control access for class members
• For example you have classes graphics objects like Circle,
Square, Rectangle etc.
• You should bundle these classes into package for the following
reasons:

1. You and other programmers can easily determine that these


classes are related.
2. You and other programmers know that where to find classes that
provide graphics related functions.
3. The name of your class wouldn’t conflict with class names in
other packages.
• For example,
– The java.lang package contains classes, such as Object, String,
and System, that are central to the Java language. Just about all
Java programs use the classes in this package.
– The java.awt package provides classes, such as Button, TextField,
and Graphics, that are used in graphical user interfaces (GUIs).
– The java.net package provides classes used for networking
tasks, and
– The java.io package provides classes used for input and output
operations.
Creating Packages
• To create a package we put the package statement at the
top of the source file in which the classes and interfaces
are defined.
package graphics;

public class Circle


{

}
• To put Rectangle the class inside graphics package, the
following code appears inside the Rectangle.java file.

• Now both Circle and Rectangle classes are in the graphics


package.
package graphics;

public class Rectangle


{

}
• if you want Circle class to available outside the package.
You must use the class fully qualified name as follows:

graphics.Circle c = new graphics.Circle( );

• This makes your code difficult to read.


import Statement
• Java provide a solution to limit the use of fully qualified name each
time you create an object.
• You can just import the class you need with import statement.
• To import a specific member into the current file, put an import
statement at the beginning of your file before any class or interface
definitions but after the package statement, if there is one.
• Here's how you would import the Circle class from the graphics
package
import graphics.Circle;

Now you can refer to Circle class by its simple name:

Circle c = new Circle( ):

To import all the classes in the graphics package you can


use * as wild card character as follows:

import graphics.*;
-End of Chapter Three-

You might also like