Chapter III
Objects and Classes in Java
By Mengistu.M(Assi.Lec).
Outlines
Objects and Classes
Object variables
Defining a class
Instance fields, Constructors, and
methods
Access Modifiers
GUI: Using Dialog Box
Objects and Classes
In Java, objects and classes are fundamental concepts of object-oriented
programming (OOP).
A class is a blueprint or a template that defines the structure and behavior of objects.
It serves as a blueprint for creating multiple instances of objects with similar
properties and methods.
Example of a simple class in Java:
public class Car {
// Fields or instance variables
String brand;
String color;
int year;
// Methods
void startEngine() {
System.out.println("Engine started!");
}
void drive() {
System.out.println("Car is driving.");
}
}
Object and class
Example of creating objects from the Car class
public class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
Car car2 = new Car();
// Accessing fields and invoking methods
car1.brand = "Toyota";
car1.color = "Red";
car1.year = 2020;
car2.brand = "BMW";
car2.color = "Blue";
car2.year = 2018;
car1.startEngine(); // Output: Engine started!
car2.drive(); // Output: Car is driving.
}}
In this example, car1 and car2 are objects created from the Car class.
Each object has its own set of field values.
We can access those fields using dot notation (objectName.fieldName)
Object variables in Java
In Java, object variables are variables that hold references to objects.
When you create an object from a class, memory is allocated to store the object's
data.
Example to illustrate object variables:
public class Car {
// Object variables
String brand;
int year;
double price;
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
Car car2 = new Car();
// Setting object variables
car1.brand = "Toyota";
car1.year = 2020;
car1.price = 25000.0;
car2.brand = "Honda";
car2.year = 2022;
car2.price = 28000.0;
// Accessing object variables
System.out.println(car1.brand + " " + car1.year + " " + car1.price);
System.out.println(car2.brand + " " + car2.year + " " + car2.price);
Cont.…
In the example above, the Car class has object
variables brand, year, and price.
When objects car1 and car2 are created,
memory is allocated to store their respective
object variables.
Each object can have different values for
these variables, as shown in the main method.
By accessing the object variables using the
dot notation (car1.brand, car2.price, etc.), you can
retrieve and modify the values associated
with each object.
Defining a class
The class serves as a blueprint for creating objects
(instances) that share the same structure and behavior.
Each instance of the class has its own set of instance
variables, which are unique to that instance.
Syntax
class ClassName: {
# Class variables
variable1 = value1
variable2 = value2
# Methods
def method1(self):
# Method1 code
def method2(self, parameter):
# Method2 code
}
Cont.…
Let's break down the different components of a class:
Class name:
This is the name you give to your class.
In the example above, the class is named ClassName.
Class variables:
These are variables shared by all objects of the class.
They are defined inside the class but outside any
methods. In the example above, variable1 and
variable2 are class variables.
Methods:
These are functions defined within the class that perform
specific actions on objects of the class. They are defined
like any other function but are typically designed to work
with the class's instance variables. In the example above,
method1 and method2 are methods of the class.
Instance fields, Constructor and methods
In Java, instance fields, constructors, and methods are
key components of defining and using objects within a
class.
What are basic concepts of instance fields,
constructors, and methods in Java?
Instance Fields:
Instance fields, also known as instance variables, are
variables declared within a class that hold data specific
to each object created from that class.
These fields store the characteristics of an object.
Each object instance has its own copy of instance
fields.
Example
public class Car {
// Instance fields
String brand;
String color;
int year;
// Constructor
public Car(String brand, String color, int year) {
this.brand = brand;
this.color = color;
this.year = year;
}
// Method
public void startEngine() {
System.out.println("The " + brand + " car has started its engine.");
} }
In the above example, brand, color, and year are instance fields of the
Car class. Each instance of the Car class will have its own values for
these fields.
Constructors:
Constructors are special methods used to initialize objects of a class.
Constructors have the same name as the class and can have parameters to set
initial values for the instance fields.
public class Car {
// Instance fields
String brand;
String color;
int year;
// Constructor
public Car(String brand, String color, int year) {
this.brand = brand;
this.color = color;
this.year = year;
}
// Method
public void startEngine() {
System.out.println("The " + brand + " car has started its engine.");
}}
In the above example, the constructor Car(String brand, String color,
int year) initializes the brand, color, and year instance fields with the
values passed as arguments.
Methods
Methods are functions defined within a class that perform specific actions.
They can access and manipulate the instance fields of an object.
Methods can have parameters and can also return values.
public class Car {
// Instance fields
String brand;
String color;
int year;
// Constructor
public Car(String brand, String color, int year) {
this.brand = brand;
this.color = color;
this.year = year;
}
// Method
public void startEngine() {
System.out.println("The " + brand + " car has started its engine.");
}
// Method with a return value
public String getBrand() {
return brand;
}
}
In the above example, startEngine() is a method that prints a
message indicating the car's engine has started. getBrand() is
another method that returns the value of the brand instance field.
Account example
setName Method
Method setName receives parameter name of type
String,double etc —which represents the name that will
be passed to the method as an argument
Parameters are declared in a parameter list, which is
located inside the parentheses that follow the method
name in the method header.
When there are multiple parameters, each is separated
from the next by a comma.
Variables declared in a particular method’s body (such
as main) are local variables which can be used only in
that method
getName Method
It returns a particular object’s name to the
caller
The return type passes the value of
instance variable name back to the caller
If void it passes nothing to its caller.
Cont.…
A class that contains a main method begins the execution of a
Java app.
Class Account cannot execute by itself because it does not
contain a main method.
if you type java Account in the command window, you’ll get an
error indicating “Main method not found in class Account.”
To fix this problem, you must either declare a separate class
that contains a main method or place a main method in class
Account.
Once main begins executing, it may call other methods in this
and other classes
Main method
Instantiating an Object—Keyword new and
Constructors
Keyword new creates a new object of the specified class.
parentheses in combination with a class name represent a
call to a constructor.
It is similar to a method but is called implicitly by the new
operator to initialize an object’s instance variables when the
object is created.
For e.g. Account acc = new Account()
Method Calling
Method calling used to execute method
definition and used to pass parameters.
When getName is called:
i. The app transfers program execution from the call
(main) to method getName’s declaration.
ii. method getName performs its task—that is, it
returns the name.
iii. System.out.printf displays the String returned
by method getName.
Access Modifiers
Data visibility and accessibility are controlled through
access modifiers.
There are three main access modifiers Protected,
Private and Public.
These modifiers define the level of access that other
classes and objects have to a particular piece of data or
method.
Private:
When a variable or method is marked as private, it is
only accessible within the same class.
It cannot be accessed or modified directly by any other
class.
Access Modifiers public, private and protected
Variables or methods declared with access modifier private are
accessible only to methods of the class in which they’re declared.
Variables or methods declared with access modifier public are
accessible by all classes.
Variables or methods declared with access modifier protected are
accessible by derived classes.
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method.
There are two levels of access control:
At the top level—public, or package-private.
At the member level—public, private, protected.
Cont.…
A class may be declared with the modifier public, in
which case that class is visible to all classes
everywhere.
If a class has no modifier (the default, also known as
package-private), it is visible only within its own package
(packages are named groups of related classes).
The private modifier specifies that the member can
only be accessed in its own class.
The protected modifier specifies that the member can
only be accessed within its own package (as with
package-private) and, in addition, by a subclass of its
class in another package.
Access Modifiers
The following table shows the access to members permitted by each modifier
GUI: Using Dialog Box
GUI is a visual way of interacting with a computer using
items such as windows, icons, and menus, used by most
modern operating systems.
showMessageDialog
JOptionPane method showMessageDialog to
display a dialog box containing a message.
The method requires two arguments.
The first helps the Java app determine where to
position the dialog box.
If the first argument is null, the dialog box is
displayed at the center of your screen.
The second argument is the String to display in the
dialog box.
JOptionPane Class static Method showInputDialog
Wolaita Sodo University, schoolof Informatics
cont.…
JOptionPane method showInputDialog to display
an input dialog containing a prompt and a field
(known as a text field) in which the user can enter
text.
Method showInputDialog’s argument is the prompt
that indicates what the user should enter.
The user types characters in the text field, then
clicks the OK button or presses the Enter key to
return the String to the program.
!
ou
ky
an
Th
Monday, May 20, 2024