0% found this document useful (0 votes)
9 views53 pages

Chapter – II Class and Object

This document provides an overview of classes and objects in programming, detailing their definitions, creation, and usage. It explains access modifiers, constructors, and methods, along with examples for better understanding. Additionally, it covers enumerated types and Java's garbage collection process.

Uploaded by

tesfahunyosef8
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)
9 views53 pages

Chapter – II Class and Object

This document provides an overview of classes and objects in programming, detailing their definitions, creation, and usage. It explains access modifiers, constructors, and methods, along with examples for better understanding. Additionally, it covers enumerated types and Java's garbage collection process.

Uploaded by

tesfahunyosef8
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/ 53

Chapter –II Class and Object

 Class and object


 Define a class
Compiled By: Daniel Tesfay

Master of Engineering in ICT Convergence


 Creating and using an object
Senior Lecturer

 Modifiers Access and Non-Access Department of Computer Science

 Method and constructor Hawassa University

 Instantiating an object 2022


Objective

At the end of this chapter, students will be able to


o understand the class and object
o demonstrate class definition
o create and use objects of a given class
o use method and constructor
o understand and use Instance fields
o Understand the modifiers/ Access Modifiers
Class

o A class is the template or blueprint from which objects are


made

o It is a collection of identical objects

o A class is a means to logically group objects that shares some


common properties and behaviour.

o Many objects are of the same kind but have different identity.

o Class is an object’s type


Class Conn…
o A class provides a method for packaging together a

group of logically related data items and function


that operates on them
o Before we create a class, we must identify

₋ Class name

₋ Data items which are called fields

₋ Functions or methods/behavior of the object


Class

o By convention, attributes’ name are suggested to be adjectives to describe

the object and the behaviors are the verbs or actions that shows action on

the object.

o For example, consider a car as an entity it would have the components:

₋ Class name/Entity Name: Car

₋ Attribute/ States : make, model, color, year, mpg

₋ Method/behaviors: moveForward(), moveBackward(), turnLeft(),

turnRight(), stop(), and honk() are methods or behaviors of a car object.


Define a class

o A class definition consists of


₋ Access modifier
₋ Class keyword
₋ Class Name
₋ State / data members
₋ Behaviour / method
₋ Constructors
Class definition Syntax
[Accesses Modifier ] <class> <ClassName> {

[Access Modifier] <Data Type> <DataMember1>;


[Access Modifier] <Data Type> <Data Member2 >;
[Access Modifier] <Return Type> <MrthodName1> ( [Para1, Para2 …]) {
//method body
}
[Access Modifier] <ClassName> ([optional Parameter lists]) {
// Constructors Body
}

} //end of the class


Class Definition
public class Account {
Example
private int accountNo;
private float balance;

public Account(int accountNo, float balance) {


this.accountNo = accountNo;
this.balance = balance;
}

public int getAccountNo() { return accountNo;}


public float getBalance() { return balance;}

public void setAccountNo(int accountNo) { this.accountNo =


accountNo;}
public void setBalance(float balance) { this.balance =
balance;}

}
Dog class definition
Example
public class Dog {
₋ This class Dog has 3 methods and instance variables.
private String breed;
₋ Methods like:- barking(), hungry(), sleeping()
private int age
₋ States like:- breed, age, color.
private String color;
void barking() { //body …………………. }
void hungry() {//body ……………………}
void sleeping() {//body ................ }
}
Extended Class
Definition
[Accesses Modifier ] <class> <ClassName> [extends] [Superclass]
[implements ] [interface1, Inteface2] {
[Access Modifier] <Data Type> <DataMember1>;
[Access Modifier] <Data Type> <Data Member2 >;
[Access Modifier] <Return Type> <MrthodName1> ( [Para1, Para2 …]) {
//method body
}
[Access Modifier] <ClassName> ([optional Parameter lists]) {
// Constructors Body
}

} //end of the class


Object

o An object is an instance of a given class

o It is a runtime entity of any class

o An object must be created using the class name and new keyword
o Syntax of Object creation
ClassName ObjectName = new CLassName();
o "new" is a keyword used to return the memory of the object.
Create an Object
o There are three steps when creating an object from a class

1. Declaration- a variable declaration with a variable name of an object type

2. Instantiation- the ‘new’ key word is used to create the object.

3. Initialization- the ‘new’ key word is followed by a constructor call. This call
initializes the new object.
Object Creation Example
Example Create an object
of Car
o Crate an object of car class named tFord
Car TFord = new Car();
Instantiating and using
objects
o Instance variables and methods are accessed via created objects.
o To access an instance variable the fully qualified path should be .
Accessing Instance
Members
Access Modifiers

o Access modifiers are keywords used as a prefix with class, method and
variables.
o Access modifies will change the meaning of certain statement
o That provides restriction of access /privilege
o In java the following access modifiers are supported
₋ Package private
₋ Public
₋ Private
₋ Protected
Package private

₋ No keyword is used to define a class or members of class as


package private.

₋ Package private access modifiers are package level

₋ So long the classes are in the same package, there is an access


privilege of members from one class to another class

₋ Classes, methods and variables can be defined as package private


Public

₋ Any class member which is defined as public would have an access


privilege from any other class regardless of the package specification

₋ It has higher access privilege than others

₋ It uses a keyword public as prefix to define a public members

₋ A class, variable, or method, interface can be defined public.

₋ By conversion, it is recommended to define methods and classes as public.


Protected

o Protected is a keyword used to define a protected member or


class
o Protected can be used with, class, method and data members
o A class members defined as a protected are accessible only by the
class which is inherited by the sub class
Protected
o The third relationship is between a class and its present and future subclasses.

o These subclasses are much closer to a parent class than to any other "outside"
classes for the following reasons:
₋ Subclasses are usually more intimately aware of the internals of a parent class
₋ Subclasses are often written by you or by someone to whom you’ve given
your source code.
₋ Subclasses frequently need to modify or enhance the representation of the
data within a parent class.
Private

o Private is the most narrowly visible, highest level of


protection that you can get.
o It is the diametric opposite of public. private methods
and variables cannot be seen by any class other than the
one in which they are defined .
o Any private data, internal state, or representations
unique to your implementation anything that shouldn’t
be directly shared with subclasses is private.
Example
class Car {
private String make; The fields/data members are defined as
private String model; Private therefore, all the fields are
private int year;
private double mpg; accessible only with in this class
private String color;
private void moveForward() {/*body*/ }
private void moveBackward() {/*body*/}
private void stop() { /*body*/} Methods are defined as private
private void turnLeft() {/*body*/ }
private void turnRight() { /*body */} and they are not accessible
private void honk() { /*body*/ }
public static void main(String[] args) {
outside of this class private
Car myCar = new Car ();
myCar.make = "Subaru";
myCar.model = "Outback";
myCar.year = 2017;
myCar.mpg = 28;
myCar.color = "red";
}
}
Summary of Access
Modifiers
o The table below shows each type of modifier, it goes from least
restrictive (public) to most restrictive (private).
Modifier Class Package Subclass Everywhere

public Y Y Y Y

protected Y Y Y N

Package private Y Y N N

private Y N N N
Constructors
o Constructors are a special methods that are used to
initialize the class and instance variables automatically
at the time of object is creation
o Constructors have the same name as the class name.
o No return type is specified for the constructor
o By default constructors are public
o Constructors can be invoked only during object creation or from
other constructors using this keyword.
Defining constructor

o General Syntax
[public] <ClassName><([parameters]) >{
//body of the constructor
}
Types of Constructor

o Java provides three types of constructors

o Default constructor

₋ A constructor which is added automatically by the compiler when the


program is compiled

₋ If you declare any constructors for a class, the Java compiler will not
create a default constructor for that class.

₋ The body of the default contractor is empty


Default Constructor:
Example
No Argument Constructor

o Constructor with no arguments is known as No-Argument


constructor.

o The signature is same as default constructor, how ever the body


can have any code given by the programmer
Example

public class DateTest{


String day;
String month;
int year;
/* This constructor provides an initial value for the members
*/
public DateTest() {
this.day="Monday";
this.month = "January"
this.year = 2011;
}
}
Parametrized Constructor

o Constructor with arguments/Parameters is known as


Parameterized constructor.

o The parametrized constructors will initialize the data members of


the given class in to its parameter values.

o The value must passed from the user when the object is created
Constructor: Example

o Consider the Car as a class. Therefore, define a constructor with


no argument with in that class
class Car {

private String make; private String model; private int year;


private double mpg; private String color;

public Car() { No Argument Constructor


}
public Car(String make, String model, int year, double mpg, String
color) {
this.make = make; this.model = model;
this.year = year; this.mpg = mpg; Parametrized Constructor
this.color = color;
}
}
Invoking a Constructor
o Constructor can be implicitly invoked when we are creating an object
o Explicitly called using this() keyword from another constructor.

o Class Car can be invoked this way


₋ Car carObj = new Car(); this line of statement will invoke the no argument
constructor
₋ It is also possible to invoke the No argument constructor from the parametrized
constructor in such a way

public Car(String make, String model, int year, double mpg, String
color) {
this(); // this line will invoke the no argument constructor
}
Example
public class Student{ Invoking the
String firstName, lastName, sex;
int age; paramconstructor using
public Student() { this() method from other
this("Dawit", "Tesfaye", 27, "Male"); constructor
}
public Student(String firstName, String lastName, int age, String
sex) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.sex = sex; Invoking the no argument
} constructor when the
public static void main(String[] args) {
Student stud1 = new Student(); object is created
}
}
Method
o A method is behavior of any object
o A method is a block of code that performs a specific
task.
o Suppose you need to create a program to create a
circle and color it. You can create two methods to
solve this problem:
₋ a method to draw the circle
₋ a method to color the circle
o It uses to divide a complex problem into smaller chunks
makes your program easy to understand and reusable.
Types of Methods

o Types of Methods

₋ Standard Library Methods: These are built-in methods in


Java that are available to use.

₋ User-defined Methods: We can create our own method


based on our requirements.
Java Built-in methods

o Categories of Built-in Methods


₋ String Methods
₋ Number Methods
₋ Character Methods
₋ Array Methods etc.
String Methods

o compareTo(), str1.compareTo(str2), it returns 0 if equal, returns


positive if str1 > str2 else returns negative

o equals(): str1.equals(str2), returns either true or false

o concat(), str1.concat(str2)

o charAt(): Returns a character by index position


String Methods conn….

o equalsIgorecase() str1. equalsIgorecase(str2)


o toUpperCase () , str. toUpperCase () ;
o toLowerCase(), str. toLowerCase(),
o trim(), Removes spaces from both sides of a String,
str.trim()
o endsWith() -Ends with specified suffix,
str1.endsWith(str2)
o length() (returns string length) str.length()
Reading Assignment

o Number Methods
o Character Methods
o Array Methods etc…
User Defined Method :
Syntax
ReturnType MethodName(DataType para1, DataType
para2, ...) {
//Method body
}
o ReturnType - It specifies what type of value a method returns
₋ void return type: a method that returns nothing
₋ None void return type: a method that returns a value of its
return type
o methodName - It is an identifier that is used to refer to the
particular method in a program.
Method

o Method body - It includes the programming statements that are


used to perform some tasks.
o The method body is enclosed inside the curly braces { … }
o Example
int addNumbers() { Return type: int
// code Method Name: addNumbers
} Method Body: code
Complex method Syntax
[Modifier] [static] <returnType> <methodName> ([Para1,
para2 .])
{
// method body
}
o Modifier - It defines access visibility (public, private, or protected)
o static
₋ none access modifier
₋ it can be accessed without creating objects.
Calling a method

o To let the method do what is specified inside the body, it has to be


called by another method or main method.

o calling Syntax for the None static method inside static method is

objectName.methodName(arguments); // if the method is void

Variable = objectName.methodName(arguments); // for none void method

System.out.print(objectName.methodName(arguments)); // none void method


Calling a method

o Calling a none static method inside instance method of the same class and
o Calling a static method in any method of the same class
₋ is possible using its signature without object reference
₋ Syntax : methodName(arguments list..);
o In both the above cases, if the call is from different classes it is must to use
object reference.
₋ Syntax : objectReference.methodName(arguments list..);
Reading assignment

o Parameter Passing
o enum (Enumerator)
o Java Garbage collector
Destroying Object

o Java uses automatic garbage collection.

o When new objects are created, the memory is automatically

allocated for them. Consequently, whenever the objects are not

referenced anymore, they are destroyed and their memory is

reclaimed.
o Java garbage collection is an automatic process.
o The programmer does not need to explicitly mark objects to be
deleted.
Enumerated Types

o An enumeration (enum) is a special data type


which contains a set of predefined constants.

o We use an enum, when dealing with values that


aren't required to change, like days of the week,
seasons of the year, colors, and so on.
Creating enum in java
o To create enum, we use enum keyword
o Syntax
<enum> <enumName>{ Example
VALUE1,
enum Colors{
VALUE2, RED,
BLUE,
VALUE3
YELLOW,
} GREEN
}
Example: using an enum
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}

public class EnumDemo {

public static void main(String[] args)


{
Colors red = Colors.RED;
System.out.println(red);
// RED
}
}
Reading Assignment

o Instance Fields
o Encapsulation
End of Chapter –II Class and
Object
 Class and object
 Define a class Compiled By: Daniel Tesfay

Master of Engineering in ICT Convergence


 Creating and using an object Senior Lecturer

 Modifiers Access and Non-Access Department of Computer Science

Hawassa University

 Method and constructor 2022

 Instantiating an object
CHAPTER III

You might also like