[go: up one dir, main page]

0% found this document useful (0 votes)
5 views49 pages

Chapter 2 - OOP for CS

Chapter Two discusses the fundamentals of Java objects and classes, emphasizing that Java is an object-oriented programming language where programs are organized into objects defined by their classes. It covers key concepts such as objects, classes, methods, constructors, and enumerated types, explaining how to create and utilize them in Java. Additionally, it highlights the importance of encapsulation, inheritance, and polymorphism in object-oriented programming.

Uploaded by

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

Chapter 2 - OOP for CS

Chapter Two discusses the fundamentals of Java objects and classes, emphasizing that Java is an object-oriented programming language where programs are organized into objects defined by their classes. It covers key concepts such as objects, classes, methods, constructors, and enumerated types, explaining how to create and utilize them in Java. Additionally, it highlights the importance of encapsulation, inheritance, and polymorphism in object-oriented programming.

Uploaded by

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

Chapter Two

Java Objects and Class

By: Sinodos G
Introduction

 Java is an object-oriented programming language


 In object-oriented programming (OOP), programs are organized into
objects
 The properties of objects are determined by their class
 Objects act on each other by passing messages
 There are some fundamental concepts of OOP

• Object • Encapsulation
• Class • Abstraction
• Polymorphism • Method
• Inheritance • Message

2
Object
 A programming entity that contains state (data) and behavior (methods).
• State: A set of values (internal data) stored in an object.
• Behavior: A set of actions an object can perform, often reporting or
modifying its internal state.
 Objects can be used as part of larger programs to solve problems.
 Example 1: Dogs
• States: name, color, breed, and “is hungry?”
• Behaviors: bark, run, and wag tail

 Example 2: Cars
• States: color, model, speed, direction
• Behaviors: accelerate, turn, change gears

3
Cont’d
 An Object has two primary components:
 state – properties of the object
 behavior – operations the object can perform

State = Properties Behavior = Method


Constructing Objects
 use the new keyword to construct a new instance of an Object.
 assign this instance to a variable with the same type of the Object

 Note: classes define new datatypes !

LightSwitch ls = new LightSwitch();

4
Class
 A class is the blueprint from which individual objects are created.

 A class defines a new data type which can be used to create


objects of that type.
 A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
 Thus, a class is a template for an object, and an object is an
instance of a class.
 Class= fields + methods Circle
centre
radius
circumference()
area()

5
Classes and Objects

 A Java program consists of one or more classes.


 A class is an abstract description of objects.
 Here is an example class:
class Dog {
...
description of a dog goes here
...
}

• Here are some objects of that class:

6
Creating objects of a class

• Object – block of memory that contains space to store all instance


variables.
• Objects are created dynamically using the new keyword. It’s called
instantiating an object.
• Example:
class_name object_name;
object_name=new class_name();
or
class_name object_name=new class_name();

• Object’s created:
• ObjectName.VariableName
• ObjectName.MethodName(parameter-list)
7
Methods
 a collection of statements that are grouped together to perform an
operation.
Creating Method
 Syntax
public static int methodName(int a, int b) {
// body
}
Explanations:
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
8
Method Calling
 a method, it should be called for using
 There are two ways in which a method is called:-
 method returns a value or
 returning nothing (no return value).

 When a program invokes a method, the program control gets


transferred to the called method. This called method then returns
control to the caller in two conditions, when −
 the return statement is executed.
 it reaches the method ending closing brace.

9
 The methods returning void is considered as call to a statement.
 Example:
System.out.println("This is tutorialspoint.com!");

 The method returning value example −


int result = sum(6, 9);

 The void Keyword


 The void keyword allows us to create methods which do not return a value.
 The void method it which does not return any value.
 Call to a void method must be a statement.

10
 Passing Parameters by Value
• While working under calling process, arguments is to be passed.
• These should be in the same order as their respective parameters in
the method specification.
• Parameters can be passed by value or by reference.
• Passing Parameters by Value means calling a method with a
parameter.
• Through this, the argument value is passed to the parameter.

11
Instance fields
 also known as instance variables.
 They are attributes or properties that belong to a specific instance
(object) of a class.
 Each object created from a class can have its own set of values for
these instance fields.

 Declaration:
• declared within a class but outside Example:
of any methods or constructors. public class Person {
• define the state of an object // Instance fields
• marked with access modifiers like private String name;
private, public, or protected to private int age;
control their visibility and access. }

12
Cont’d

Initialization:
• Instance fields can have default values if not explicitly
initialized.

Example,
• numeric types are initialized to 0, and reference types
(like objects) are initialized to null.

public class Person {


private String name = "John";
private int age = 30;
}

13
Cont’d
 Access:
• Instance fields are accessed using the dot (.) notation
• Each object has its own set of field values.
Person person1 = new Person();
person1.name = "Alice";
Example: person1.age = 25;
Person person2 = new Person();
person2.name = "Bob";
person2.age = 40;
 Scope:
• Instance fields exist as long as the object they are associated
with is in memory.
• They are used to store and manage the object's data, and they
are not shared across different instances of the class.
14
Enumerated types

 referred to as enums,
 special data type used to define a set of constant values
 are a data type in computer programming that define a set
of named constant values.
 powerful for creating well-structured code.
 used to represent a fixed set of related constants
 used to represent a finite, discrete set of options or
choices.
 useful to improve code readability and maintainability

15
Cont’d …
 To create an enum, use the enum keyword
 Constants must be in uppercase letters
 Example:
 Example
enum Color {
enum Level { RED,
LOW,
GREEN,
MEDIUM,
BLUE
HIGH
}
}
Color selectedColor =
 can access enum constants with the dot Color.GREEN;
 Example:
 Level myVar = Level.MEDIUM;

16
Cont’d . . .
Example:
 write a java program tat check if today is Sunday using java
enumerated.

enum Day {
SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
if (today == Day. SUNDAY) {
FRIDAY, SATURDAY
System.out.println(“day is SUNDAY");
}
else
public class EnumDay{
System.out.println(“ not Sunday ");
public static void main(String[] args) {
}
Day today = Day. SUNDAY;
}
}

17
Cont’d
• Enums are often used in switch statements to check for
corresponding values:
switch(myVar) {
enum Level { case LOW:
LOW, System.out.println("Low level");
MEDIUM, break;
HIGH case MEDIUM:
} System.out.println("Medium level");
break;
public class Main {
case HIGH:
public static void main(String[] args) {
System.out.println("High level");
Level myVar = Level.MEDIUM; break;
}
}
}
18
Enum and loops

 The enum type has a values() method, which returns an array of all
enum constants.
 This method is useful when you want to loop through the constants
of an enum:
enum Level {
LOW, MEDIUM, HIGH
}
 Example: }
public class Main {
public static void main(String[] args) {
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
}

19
Constructors
 a special method that is used to initialize objects.
 called when an object of a class is created.
 It can be used to set initial values for object attributes
 fundamental building blocks of classes
 Constructor is invoked at the time of object creation.

 Purpose:
• are special methods used to create and initialize objects of a class.
• called when an object is instantiated (created) using the new
keyword.

 Naming:
• have the same name as the class, and they do not have a return type,
not even void.
20
Cont’d

Rules for creating constructor


• Constructor name must be same as its class name
 Constructor Name=Class Name
• Constructor must have no explicit return type

Example:

public class Person {


// Constructor

public Person() {
// Initialization code goes here
}
}

21
Cont’d

 Types of constructors
 Default Constructor
 Parameterized Constructor
 Copy Constructor:
• Creates a new object by copying the values from an existing
object.
 Static Constructor
 Private Constructor:
• Used to prevent the instantiation of a class, often in singleton
design patterns.

22
Cont’d

Types of Constructors
• Default constructor (No-argument constructor)
• A constructor that have no parameter
• Default values to the object like 0, null etc. depending on the type.
<class_name>()
{
}

• Parameterized constructor
• A constructor that have parameters
• Used to provide different values to the distinct objects.
<class_name>(parameter list)
{
}
23
Example
class Student {
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
} class_name object_name=new class_name();

24
Example:

class Student{
int id;
String name;
public static void main(String args[]){
Student(int i,String n){ Student s1 = new Student(111,“Abay");
id = i;
name = n; Student s2 = new Student(222,“Gebissa");
}
s1.display();
void display(){ s2.display();
}
System.out.println(id+" "+name);
}
}

25
Cont’d
Example:
public class Main {
int x;
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main aa = new Main();
// Create an object of class Main (This will call the constructor)
System.out.println(aa.x);
// Print the value of x
}}

26
Cont’d

 Example: Constructor wit parameters


public class Main {
int x;
public Main(int y) {
x = y;
}
public static void main(String[] args) {
Main aa = new Main(5);
System.out.println(aa.x);
}
}

27
Java - Methods
 a collection of statements that are grouped together to perform an
operation. Example:
• When you call the System.out.println() method, the system actually
executes several statements in order to display a message on the
console.
 Creating Method
 Considering the following example to explain the syntax of a method

 Syntax
public static int methodName(int a, int b) {
// body
}

28
Cont’d

 Constructor Overloading
• a technique in which a class can have any number of
constructors that differ in parameter lists.
• The compiler differentiates these constructors by taking into
account the number of parameters in the list and their type.

 Method Overloading
• class have multiple methods by the same name but different
parameters, it is known as Method Overloading.

29
Example: Constructor Overloading
class Student{
int id; void display(){
String name; System.out.println(id+" "+name+" "+age);
int age; }
Student(int i,String n){ public static void main(String args[]){
id = i; Student s1 = new
name = n;
Student(111,“yemane");
}
Student(int i,String n,int a){ Student s2 = new
id = i; Student(222,"Aryan",25);
name = n; s1.display();
age=a; s2.display();
} }
}

30
Methods
 a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 used to perform certain actions, and they are also known as functions.
 Objects interact with each other by passing messages.
 Purpose
• functions defined within a class to perform specific tasks or
operations.
• They define the behavior of the class and enable you to encapsulate
functionality.
 Naming
• Methods have names that are relevant to the action they perform.
• They can have various return types, including void for methods that do
not return a value.
31
Cont’d

public class Calculator {


// Method to add two numbers and return the result
public int add(int num1, int num2) {
return num1 + num2;
}

// Method with no return value


public void dispaly(String message) {
System.out.println(message);
}
}

32
Cont’d

Example: Methods with parameters

public class Main {


static void myName(String fname) {
System.out.println(fname + " Sinodos");
}

public static void main(String[] args) {


Name(“Abel");
Name(“Marta");
Name(“Yonas");
}
}
33
Method Overloading
 Refer to the multiple methods with the same name in a class, as
long as they have different parameter lists.

public class Calculator {


public int add(int num1, int num2) {
return num1 + num2;
}

public double add(double num1, double num2)


{
return num1 + num2;
}
}

34
Cont’d
Example:
static int add(int x, int y) {
return x + y;
}
static double add(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int num1 = add(8, 5);
double num2 = add(4.3, 6.26);
System.out.println("int: " + num1);
System.out.println("double: " + num2);
}
35
Example of Method

public class AddIntegers {


public static void main(String[] args) {
int num1 = 5;
int num2 = 7;
int sum = addNumbers(num1, num2);
System.out.println(“Sum: " + sum);
}

public static int addNumbers(int a, int b) {


return a + b;
}
}

36
Example – Constructor

public class AddIntegers {


private int num1;
private int num2; public static void main(String[] args) {
// Create an object of the AddIntegers class and pass the
// Constructor to initialize the two integers two integers to the constructor
public AddIntegers(int num1, int num2) { AddIntegers adder = new AddIntegers(5, 7);
this.num1 = num1;
this.num2 = num2; // Call the add() method to get the result
} int sum = adder.add();

// Method to add the two integers System.out.println("The sum of the two integers is: " +
public int add() { sum);
return num1 + num2; }
} }

37
Access Modifiers
 are keywords that determine the visibility or accessibility of classes,
methods, fields, and other members within a program.
 There are four main access modifiers in Java:
• public: Accessible from anywhere.
• protected: Accessible within the same package and in subclasses.
• default: Accessible only within the same package.
• private: Accessible only within the same class.

 Additionally, Java provides two more access modifiers for classes:


• final: A final class cannot be extended (subclassed).
• abstract: An abstract class cannot be instantiated on its own and is
meant to be subclassed.

38
Cont’d

 Example:
public class Numbers {
final int x = 10;
final double pi = 3.14;
public static void main(String[] args) {
Find Output?
Numbers aa = new Numbers();
aa.x = 50;
aa.PI = 25;
System.out.println(aa.x);
System.out.println(pi.x);
}
}

39
Cont’d
public class Main {
static void myStaticMethod() {
System.out.println("Static methods . . .");
} • A static method means that
it can be accessed without
// Public method
creating an object of the
public void myPublicMethod() { class, unlike public:
System.out.println("Public methods . . .");
} public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); error

Main aa = new Main(); // Create an object of Main


aa.myPublicMethod(); // Call the public method
}
}
40
Cont’d

• Difference between constructor and method


Constructor Method
• Constructor is used to initialize the • Method is used to expose
state of an object. behaviour of an object.
• Constructor must not have return
• Method must have return type.
type.
• Constructor is invoked implicitly. • Method is invoked explicitly.
• The java compiler provides a default
• Method is not provided by
constructor if you don't have any
compiler in any case.
constructor.
• Constructor name must be same as • Method name may or may not
the class name. be same as class name.

41
Encapsulation
 A fundamental principles of object-oriented programming in Java.
 Means make sure that "sensitive" data is hidden from users.
• declare class variables/attributes as private
• provide public get and set methods to access and update the value
of a private variable
 Bundling of data (attributes or fields) and methods (functions) that
operate on that data into a single unit, known as a class.
 The class is typically declared as private, and access to that data is
controlled through public methods, which are called getters and
setters.
 This ensures that the data is only accessed and modified in a
controlled and consistent manner, promoting data integrity and
security.

42
Cont’d
 Encapsulation is one of the four fundamental OOP concepts.
 The other three are inheritance, polymorphism, and
abstraction.
 a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit.
 Variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.
 To achieve encapsulation in Java −
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and
view the variables values.

43
Example

public class EncapTest {


private String name;
private String idNum;
public void setAge( int newAge) {
private int age; age = newAge; }
public int getAge() { public void setName(String newName) {
name = newName; }
return age; } public void setIdNum( String newId) {
public String getName() { idNum = newId;
}}
return name; }
public String getIdNum() {
return idNum; }

44
Cont’d
 The public setXXX() and getXXX() methods are the access points of the
instance variables of the EncapTest class.
 Normally, these methods are referred as getters and setters. Therefore,
any class that wants to access the variables should access them
through these getters and setters.
 The variables of the EncapTest class can be accessed using the
following program:
public class RunEncap {
public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()); } }

45
Cont’d

 Key aspects of encapsulation


• Data Hiding
• Public Methods
• Access Control:
• Defines which methods and data members are accessible to
the outside world and which are kept private.

• Information Abstraction:
• abstracts the implementation details of a class and focuses on
what the class can do rather than how it does it.

46
Benefits of encapsulation
 Data Protection
• prevent accidental or unauthorized modifications
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.
 Flexibility
• allows you to change the internal implementation of a class
without affecting the code that uses the class
 Code Maintainability
• It promotes code organization and makes it easier to understand
and maintain by providing a clear and well-defined structure.
 Reusability
• used as building blocks in different parts of a program or in
different programs altogether, enhancing code reusability.
47
Example
public class Student { // Public setter method for name
// Private fields (data) public void setName(String name) {
private String name; this.name = name;
private int age; }

// Public constructor // Public getter method for age


public Student(String name, int age) { public int getAge() {
this.name = name; return age;
this.age = age; }
}
// Public setter method for age

// Public getter method for name


public void setAge(int age) {
public String getName() { if (age >= 0) {
return name; this.age = age;
} }
}
48 }
Question

End of Chapter 2

Next  Chapter 3

49

You might also like