0% found this document useful (0 votes)
8 views29 pages

CHAPTER 33

Chapter Three discusses the fundamental concepts of classes and objects in Java, emphasizing that a class serves as a blueprint for creating objects, which are instances of that class. It explains the structure of classes, including member variables and methods, and introduces constructors for initializing objects. Additionally, the chapter covers method overloading, the use of the 'this' keyword, and the automatic garbage collection process in Java.

Uploaded by

abdatadalacha5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

CHAPTER 33

Chapter Three discusses the fundamental concepts of classes and objects in Java, emphasizing that a class serves as a blueprint for creating objects, which are instances of that class. It explains the structure of classes, including member variables and methods, and introduces constructors for initializing objects. Additionally, the chapter covers method overloading, the use of the 'this' keyword, and the automatic garbage collection process in Java.

Uploaded by

abdatadalacha5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter-Three

3. Classes and Objects in Java

• The class is at the core/ blueprint of Java programming.


• It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
• As such, the class forms the basis for OOP in Java.
• In object-oriented terms, we say that Chala’s bicycle is an instance of the
class of bicycle objects.
• A class is the blueprint from which individual objects are created.

1
What is an Object?

• An object is a software package of related states and behaviour.


• Software objects are often used to model the real-world objects you find in everyday life.
• An object is also known as an instance.
• The variables of an object are formally known as instance variables because they contain
the state of a particular object. In general an object is:-
 a real world software entity
 a runtime entity
 which has state and behavior
 which is an instance of a class.
2
Class
What is class?
• A class is a blueprint or prototype from which objects are created.
• A class is used to create an object (it is a collection of objects of similar type)
• A class is a blueprint that defines the variables and methods common to all
objects of a certain kind and declares the instance variables necessary to
contain the state of every object.
• The class contains different variables with their attributes.
• A class is also known as a container for code.
Example

class Increment {
public static void main(String[] args) {
int x = 12,y = 12;
System.out.println(x++);// printed & then incremented
System.out.println(x);
System.out.println(++y);// incremented & then printed
System.out.println(y);
}}
Output
12 13 13 13
Declaring Member Variables
There are several kinds of variables:
• Member variables in a class are called fields.
• Variables inside a method or block of code are called local variables.
• Variables inside method declarations are called parameters.
• A class is declared by use of the class keyword.
Inside a class, it is possible to define:-
 Data Elements, usually called Instance Variables.
 Functions are usually called Methods. E.g.

5
Example Class Book with its instance
variables
class Book {
String title;
String author;
int numberOfPages;
} // This instance variable can be accessed by dot notations.
class ExampleBooks {
public static void main(String[] args) {
Book b = new Book();
b.title = "Thinking in Java";
b.author = "Bruce Eckel";
b.numberOfPages = 1129;
System.out.println(b.title + " : " + b.author +
• " : " + b.numberOfPages);
}} Output Thinking in Java : Bruce Eckel : 1129
Con’t...

public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age); }

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31); } }
In general Class declaration:-
class class-name
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type method nameN(parameter-list)
{
// body of method
8
} }
Con’t…
• The data, or variables, defined within a class are called instance variables.

• The code is contained within methods.

• Collectively, the methods and variables defined within a class are called
members of the class.

• In most classes, the instance variables are acted upon and accessed by the
methods defined for that class.

• Variables defined within a class are called instance variables because each class
instance (that is, each object of the class) contains its copy of these variables.

• Thus, the data for one object is separate and unique from the data for another. 9
Declaring Objects
• Every object we use in a program must be declared.

• An object declaration defines the name of an object and the class to which the
object belongs.

• Its syntax is <class name><object names>;

• Where <object names> is a sequence of object names separated by commas and

• <class name> is the name of a class to which these objects belong.

• Here is how the general syntax is matched to the object declaration of the program.

• MainWindow, mainWindow;

(class name) (object name) 10


Con’t…

• Here are more examples

Account checking;

Customer John, Jack, Kebede;

• The first declaration declares an Account object named checking, and the second
declares three customer objects.

• To declare an object as an instance of some class, the class must be defined already.

• An identifier is a sequence of letters, digits, underscores, and dollar signs with the first
being a letter.

• The name should start with a letter or an underscore (_) and cannot start with a digit.
11
Object Creation
• An object declaration declares the name (identifier), which we use to refer
to an object.

• For example the declaration Account account; labels that the name
account is used to refer to the Account object, but the actual Account
object is not yet created.

• We create an object by invoking the new command.

• The syntax for new is

• <object name> = new <class name> ( <arguments>);


12
Con’t…
• Where <object name> is the name of a declared object, <class name> is the
name of the class to which the object belongs, and <arguments> is a
sequence of values passed to the method.

• Let’s match the syntax to the actual statement in the sample program.

mainWindow = new MainWindow();

• We can pass an argument in the new command to specify the title of the
window.
• mainWindow = new MainWindow(“This is my First Window”); change the title of the window to
13
Constructors
• A class contains constructors that are invoked to create objects from the
class blueprint.

• Constructor declarations look like method declarations except that they


use the name of the class and have no return type.

• A constructor initializes an object immediately upon creation.

• Constructors can be default or parameterized constructors.

• A default constructor is called when an instance is created for a class.

14
Cont.

• Role: object initialization

• The name of the constructor must be the same as that of the class name.

• Must not have a return type.

• Every class should have at least one constructor.

• If you don’t write a constructor, the compiler will generate the default constructor.

• Constructors are usually declared public.

• Constructor can be declared as private → You can't use it outside the class.

• One class can have more than one constructor.

• Constructor overloading. 15
Cont.…

• In general, the constructor allows to:-

• The creation of instances that are properly initialized.

• the constructor is a method that:-

1. Has the same name as the name of the class to which is belons to

2. Has no specification for the return value, since it returns nothing.


Cont.…

class Book { // the class name book


String title;
String author;
int numberOfPages;
Book(String tit,String aut,int num) {
title = tit;
author = aut;
numberOfPages = num; }}
class ExampleBooks2 { // Constructor
public static void main(String[] args) {
Book b = new Book("Thinking in Java","Bruce Eckel",1129);
System.out.println(b.title + " : " + b.author +
" : " + b.numberOfPages);
}}
• Example are:””+x+” “+y”+” “+z”);
Class demo }
{ }
int x; Class demo main
int y; {
float z; Public static void main(String args[])
demo() {
{ demo d1=new demo(); //This is a call for the
X=1; above default constructor

Y=2; d1.display();

Z=3; }

} }

void display()
{
System.out.println(“values of x, y and z
18
This Keyword
• Sometimes a method will need to refer to the object that invoked it.
• To allow this, Java defines the this keyword. this can be used inside any method to refer to
the current object.
• That is, this is always a reference to the object on which the method was invoked.
• Example: System.out.println(“values of x, y and z
Class demo are:”+x+” “+y”+” “+z”);
{ }
int x; }
int y; Class demo main
float z; {
demo(int x,int y,int z) Public static void main(String args[])
{ {
this.x=x; demo d1=new demo(1,2,3); // this is a call for the
above-parameterized constructor
this.y=y;
d1.display();
this.z=z;
}
}
}
void display()
Output: 19
{
Garbage Collection
• Since objects are dynamically allocated by using the new operator, objects
are destroyed and their memory released for later reallocation.

• In some languages, such as C++, dynamically allocated objects must be


manually released by use of a delete operator.

• Java takes a different approach; it handles deallocation for you


automatically.

• The technique that accomplishes this is called garbage collection.

20
• It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
The finalize( ) Method
• Sometimes an object will need to perform some action when it is destroyed.
• For example, if an object is holding some non-Java resource such as a file handle or
window character font, then you might want to make sure these resources are freed before
an object is destroyed.
• To handle such situations, Java provides a mechanism called finalization.
• The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
} 21
• Here, the keyword protected is a specifier that prevents access to finalize( ) by code
Methods
• The only required elements of a method declaration are the method's return type,
name, a pair of parentheses, (), and a body between braces, {}.

• Two of the components of a method declaration comprise the method signature—


the method's name and the parameter types.

• More generally, method declarations have six components, in order:


• Modifiers—such as public, private.
• The return type—the data type of the value returned by the method, or void if
the method does not return a value.

22
Con’t
• The method name—the rules for field names apply to method names as well, but

the convention is a little different.

• The parameter list in parenthesis—a comma-delimited list of input parameters,

preceded by their data types, enclosed by parentheses, ().

• If there are no parameters, you must use empty parentheses.

• The method body, enclosed between braces—the method's code, including the

declaration of local variables, goes here.


23
Overloading Methods

• The Java programming language supports overloading methods, and Java can
distinguish between methods with different method signatures.

• This means that methods within a class can have the same name if they have
different parameter lists.

• Suppose that you have a class that can use writing to draw various types of data
(strings, integers, & so on) & contains a method for drawing each data type.

• It is bulky to use a new name for each method—for example, drawString,


drawInteger, drawFloat, and so on.
24
example
public class DrawArtist {
...
public void draw(String s) {
...
}
public void draw(int i) { ...
}
public void draw(double f) { ...
}
public void draw(int i, double f) { ...
}} 25
Con’t

• Overloaded methods are differentiated by the number and the type of the
arguments passed into the method.

• In the code sample, draw(String s) and draw(int i) are distinct and unique
methods because they require different argument types.

• You cannot declare more than one method with the same name and the same
number and type of arguments, because the compiler cannot tell them a part.

• The compiler does not consider return type when differentiating methods, so
you cannot declare two methods with the same signature even if they have a
26
different return type.
Overloading Constructors
We can overload constructor methods
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
27
return width * height * depth; }}
END
Thank you
?
Quiz 5%
• Discuss class and objects in detail
• Write the syntax used to declare and create an object
• Discuss constructor
• Discuss method overloading
• List the components of methods.

You might also like