Chapter-4 OOP - UP
Chapter-4 OOP - UP
1
Classes
• Java is an object-oriented programming language.
• Everything in Java is associated with classes and
objects, along with its attributes and methods.
• For example: in real life, a car is an object. The
car has attributes, such as weight and color, and
methods, such as drive and brake.
• A Class is like an object constructor, or a
"blueprint" for creating objects.
• More examples: students are learning java.
What is students and java in above statement?
2
Create a Class
• Object means a real word entity such as pen, chair, table etc
• An object has three characteristics: state, Behavior and Identity
• Software objects are modeled after real-world objects in
that they too have state and behavior.
– A software object maintains its state in one or more variables.
– A variable is an item of data named by an identifier. A software
object implements its behavior with methods.
– Definition: An object is a software bundle of variables
and related methods.
– An object is also known as an instance of class. An
instance refers to a particular object.
• For e.g. Hora’s bicycle is an instance of a bicycle - It
refers to a particular bicycle.
4
•
Object…..
• The variables of an object are formally known as
instance variables.
• In a running program, there may be many
instances of an object.
– For e.g. there may be many Student objects.
• Each of these objects will have their own instance
variables and each object may have different
values stored in their instance variables.
– For e.g. each Student object will have a different
number stored in its StudentNumber variable.
5
Objects
• Object’s variables make up the
center, or nucleus, of the object.
• Methods surround and hide the
object’s nucleus from other objects
in the program.
• Encapsulation refers to the practice
of enclosing an object's variables
within the protective custody of its
methods.
• Encapsulation has two benefits for
software developers:
6
Objects…
• Benefits of Encapsulation
– Modularity: The source code for an object can be
written and maintained independently of the source
code for other objects. Also, an object can be easily
passed around in the system. You can give your
bicycle to someone else, and it will still work.
– Information-hiding: An object has a public interface
that other objects can use to communicate with it.
The object can maintain private information and
methods that can be changed at any time without
affecting other objects that depend on it.
7
Object…..
• In Java, an object is created from a class. We have
already created the class named Student, so now
we can use this to create objects.
• To create an object of Student, specify the class
name, followed by the object name, and use the
keyword new:
• Example: Create an object called "myObj"
• Shortly, Object can be defined as an instance of a
class
8
Object …..
• To create an object of Student, specify the class name,
followed by the object name, and use the keyword
new:
• Example: Create an object called "myObj"
• Student myObj=new Student();
• Here,
• Student is class name and
• myObj is instance of class (object name)
9
Create two objects of Student: myObj and myObj2
10
Using Multiple Classes
Example of three classes
• Car Class: The Car class represents a car object with its brand
and model. It has a constructor to initialize the brand and model
instance variables and a start() method to print a message
indicating the car is starting.
• Driver Class: The Driver class represents a driver object with its
name and age. It has a constructor to initialize the name and age
instance variables and a drive() method that takes a Car object as a
parameter and prints a message indicating the driver is driving the
specified car.
• Main Class: The Main class contains the main method, which
serves as the entry point of the program. Inside the main method,
you create instances of the Car and Driver classes, and invoke
their methods to demonstrate the interaction between the objects.
11
Car class
public class Car {
private String brand;
private String model;
public Car(String brand, String model) {
this.brand = brand;
this.model = model;
}
public void start() {
System.out.println("The " + brand + " " + model + " is starting.");
}
} 12
Driver class
public class Driver {
private String name;
private int age;
public Driver(String name, int age) {
this.name = name;
this.age = age;
}
public void drive(Car car) {
System.out.println(name + " is driving the " + car.getBrand() + " " + car.getModel() + ".");
}
}
13
Main class
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry");
Driver driver = new Driver("John", 25);
driver.drive(myCar);
myCar.start();
}
}
14
Java constructors
• A constructor in Java is a special method that is used to
initialize objects.
• The constructor is called when an object of a class is
created. It can be used to set initial values for object
attributes:
• The constructor name must match the class name, and it
cannot have a return type (like void).
• All classes have constructors by default: if programmer do
not create a class constructor yourself, Java creates one for
programmer.
• Two types of constructor:
1.Default constructor (no-arg constructor)
2. Parameterized constructor 15
constructor
• The constructor in Java cannot be abstract, static, final or synchronized
and these modifiers are not allowed for the constructor.
• Means:
• Abstract: An abstract method is a method without an implementation. It is
meant to be overridden by subclasses. Constructors cannot be abstract
because they must provide an implementation for initializing the object.
• Static: A static method is a method that belongs to the class itself, rather than
an instance of the class. Constructors cannot be static because they are used
to create instances of a class.
18
Parameterized Constructors
• A constructor which has a specific number of parameters is called
parameterized constructor.
• It is used to provide different values to the distinct objects
// compute and return volume
Example:
double volume() {
/* Here, Box uses a parameterized
constructor to return width * height * depth;
initialize the dimensions of a box. }}
*/ class BoxDemo7 {
class Box { public static void main(String args[]) {
double width; // declare, allocate, and initialize Box objects
double height; Box mybox1 = new Box(10, 20, 15);
double depth; Box mybox2 = new Box(3, 6, 9);
Box(double w, double h, double d) // double vol;
This is the constructor for Box. vol = mybox1.volume(); // get volume of first box
{ System.out.println("Volume is " + vol);
width = w; vol = mybox2.volume(); // get volume of second box
height = h; System.out.println("Volume is " + vol);
depth = d; }
} } 19
Parameterized Constructors….
Box mybox1 = new Box(10, 20, 15);
The values 10, 20, and 15 are passed to the Box( )
constructor when new creates the object. Thus,
mybox1’s copy of width, height, and depth will contain
the values 10, 20, and 15 respectively.
20
Overloading Constructors Example:
/* Here, Box defines three constructors to
// compute and return volume
initialize
double volume() {
the dimensions of a box various ways. return width * height * depth;
*/ }
class Box { }
double width; class OverloadCons
double height; {
double depth; public static void main(String args[])
{
// constructor used when all dimensions specified
// create boxes using the various constructors
Box(double w, double h, double d) { Box mybox1 = new Box(10, 20, 15);
width = w; Box mybox2 = new Box();
height = h; Box mycube = new Box(7);
depth = d; } double vol;
// constructor used when no dimensions specified // get volume of first box
Box() { vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
width = -1; // use -1 to indicate
// get volume of second box
height = -1; // an uninitialized vol = mybox2.volume();
depth = -1; // box } System.out.println("Volume of mybox2 is " + vol);
// constructor used when cube is created // get volume of cube
Box(double len) { vol = mycube.volume();
width = height = depth = len; System.out.println("Volume of mycube is " + vol);
}} }
21
Java Class Attributes
• It is the properties of an entity or an object of a class.
• In the programming, the term variable can replaced by
name of attributes.
• Attribute is also called fields/column.
• Attributes can accessed by creating an object of the class,
and by using the dot syntax (.) like method.
• modify attribute values or override existing values is
possible. But, if declare within final and/ static keyword,
it cannot modified the original final of variables.
• Example:
private double radius;
double radius;
22
Example of constructor and attributes
23
Example of cannot modify attribute values: declared by “final”
24
Java Methods
• A method is a block of code which only runs when it is
called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are
also known as functions.
• Why use methods? To reuse code: define the code once,
and use it many times.
• Methods are mechanisms used to implement operations
in classes are called methods.
• Methods define the behavior of a class and the objects
created from the class.
25
Methods……..
26
Create a Method
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses ( ).
• Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own
methods to perform certain actions:
• Example: Create a method inside Student:
27
Cont’s
28
Example: Inside Student, call the myMethod()
method:
29
Multiple methods
30
Static vs Public Method
• Java programs have either static or public methods and
also static or public attributes.
Static method: it can be accessed without creating an
object of the class.
Public method which can only be accessed by objects of
class.
31
Example: of Static and Public method
32
Java Method Parameters
Parameters and Arguments
• Information can be passed to methods as parameter.
• Parameters act as variables inside the method.
• Parameters are specified after the method name, inside
the parentheses. You can add as many parameters as you
want, just separate them with a comma.
• The following example has a method that takes a String
called fname as parameter. When the method is called,
we pass along a fname, which is used inside the method
to print the full name:
33
34
Cont’s
• When a parameter is passed to the method, it is called
an argument. So, from the example above: fname is a
parameter, while Abdi, Bonsa and Gamachu are
arguments.
Multiple Parameters:
35
Cont’s
36
More examples: return values
37
• Arguments:
• Arguments are the actual values provided to a method
when it is invoked or called.
• Arguments are specific values that are passed into the
method to be used by the corresponding parameters.
• Arguments can be literals, variables, or expressions that
evaluate to the expected parameter types.
• The number and order of the arguments must match the
number and order of the parameters defined in the method.
public static void main(String[] args) {
mymethod(“Haro, Galchu!");
}
In this example, “Haro, Galchu!" is an argument passed to the
mymethod method during its invocation. It matches the String
parameter message defined in the method's declaration. 38
Java Method Overloading
• Method overloading allows you to define multiple
methods with the same name but different parameter
lists within the same class.
• The overloaded methods must have different parameter
types, different number of parameters, or both.
• Overloaded methods are differentiated based on the
number, type, and order of the parameters.
• Overloading enables you to provide different ways of
performing similar operations or actions with different
input parameters.
• Overloaded methods may or may not have the same
return type.
39
Example of method overload
40
Method Overriding:
42
Modifiers in java
• In Java, modifiers are keywords that are used to specify
the properties and behaviors of classes, variables,
methods, and other program elements.
• Modifiers control the accessibility, visibility, and
behavior of these elements within the program.
modifiers divide into two groups:
• Access Modifiers - controls the access level
• Non-Access Modifiers - do not control access level, but
provides other functionality
43
Access Modifiers
For attributes, methods and constructors, you can use the one of the
following:
public: The element is accessible from anywhere, both within the
same class and from other classes.
– Public data members can be accessed and modified directly without the
need for getter and setter methods.
private: The element is only accessible within the same class. It is not
visible to other classes. Private data is not visible or accessible from
outside the class, including other classes and subclasses.
– Access to private data is usually provided through public methods, such
as getter and setter methods, allowing controlled access and
manipulation of the data.
protected: The element is accessible within the same class,
subclasses, and other classes in the same package.
No modifier (default): The element is accessible within the same
package but not from outside the package.
44
Simple example of private access modifier
In this example, we have created two classes AB and BC. A class
contains private data member and private method.
We are accessing these private members from outside the class,
so there is compile time error.
class AB{
private int age=50;
private void msg(){System.out.println("Hello java");}
}
public class BC{
public static void main(String args[]){
AB obj=new AB();
System.out.println(obj.age);//Compile Time Error
obj.msg();//Compile Time Error
}} 45
Role of Private Constructor
If you make any class constructor private, you cannot
create the instance of that class from outside the class.
For example:
class AB{
private AB(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class BC{
public static void main(String args[]){
AB obj=new AB();//Compile Time Error
}
} 46
Default Access Modifier example
• In this example, we have created two packages A and B. We are accessing the AB
class from outside its package, since AB class is not public, so it cannot be
accessed from outside the package.
//save by AB.java
package A;
class AB{
void msg(){System.out.println("Hello");}
}
//save by BC.java
package B;
import AB.*;
class BC{
public static void main(String args[]){
AB obj = new AB();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class AB and its method msg() is
47
default so it cannot be accessed from outside the package.
example of Protected Access Modifier
//save by AB.java
package A;
public class AB{
protected void msg(){System.out.println(“IT");}
}
//save by BC.java
package B;
import A.*;
class BC extends AB{
public static void main(String args[]){
BC obj = new BC();
obj.msg();
}
}
48
Example of Public Access Modifier
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
Example:
//save by AB.java
package A;
public class AB{
public void msg(){System.out.println("Hello");}
}
//save by BC.java
package B;
import A.*;
class BC{
public static void main(String args[]){
AB obj = new AB();
obj.msg();
}
} 49
50
Non-Access Modifiers:
static: The element belongs to the class itself, rather than an
instance of the class. It can be accessed without creating an object
of the class.
final: The element cannot be modified once it is assigned a value
or defined. For variables, it makes them constants. For methods, it
prevents them from being overridden in subclasses. For classes, it
prevents inheritance.
abstract: The element is incomplete and must be implemented in a
subclass (it must be inherited from another class). It is used for
abstract classes and methods.
synchronized: The element is thread-safe and can be accessed by
multiple threads concurrently while ensuring data integrity.
volatile: The element's value is always read from and written to
main memory, ensuring visibility across multiple threads.
transient: The element is not serialized when an object is
51
converted to a byte stream.
Non-Access Modifiers:
52
this keyword in java
53
Example of this
56
Package…
• It is possible to create a hierarchy of packages.
The general form of a multileveled package
statement is
• shown here: package pkg1[.pkg2[.pkg3]];
57
Assignment
58
?
59