0% found this document useful (0 votes)
17 views61 pages

OOP Chap 2 Deber Markose

The document discusses object oriented programming concepts including classes, objects, instance fields, constructors and methods. It explains how to define a class, create objects, and access members of a class using objects.
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)
17 views61 pages

OOP Chap 2 Deber Markose

The document discusses object oriented programming concepts including classes, objects, instance fields, constructors and methods. It explains how to define a class, create objects, and access members of a class using objects.
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/ 61

Debre Markos University

Burie Campus
Department of Computer Science

Object Oriented programming

Lecture 2:
Objects and Classes

Ayisheshim Almaw
ayishu165@gmail.com

1
outlines
 Defining a class
 Creating an Object
 Instantiating and using objects
Printing to the Console
Methods and Messages
Parameter Passing
Comparing and Identifying Objects
Destroying Objects
Enumerated Types
 Instance fields
 Constructors and Methods
 Access Modifiers
 Encapsulation
2
Introduction
Object-Oriented programming:
• OOPS is a programming approach which provides solution to
real life problems with the help of algorithms based on real
world.
• It uses real world approach to solve a problem.
• Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects.
• It simplifies the software development and maintenance by providing
some concepts:
 Objects
 Classes
 Inheritance
 Polymorphism
 Abstraction 3
Advantages of Object Oriented Programming
• Code recycle and reuse.
• Wrapping up of data into a single unit.
• Easy to partition the work in a project based on objects.
• Software Complexity can be easily handled and
managed.
• Possible to map objects in a problem domain within a
program.
• Data hiding is possible.
• Use of inheritance can eliminate redundant codes in a
program.

4
class
• A class is a group of objects that has common properties.
A class is a template, blue print, or contract that defines what
an object’s data fields and methods will be.
• two classes can put into one file, but only one class in the
file can be a public class.
• The public class must have the same name as the file name.
Defining a Class
• o define a class the class keyword is followed by the name
of the new type. For example:
class ClassTypeName {
/*class body goes here*/
} 5
Car class
Class: Car
Properties
(Describe)
Company
Model Methods
Color (Functions)
Mfg. Year Start
Price Drive
Fuel Type Park
Mileage On_break
Gear Type On_lock
Power Steering On_turn
Anti-Lock
braking system
6
Objects of Class Car

Honda City Hyundai i20 Sumo Grand

Mercedes E class Swift Dzire

7
object
• represents an entity in the real world that can be distinctly identified.
• An object is an instance of a class.
• In real-world an entity that has state and its behavior is known as an
object.
• Example: A dog has
states - color, name, breed as well as
behaviors – wagging the tail, barking, eating.
• The state of an object is stored in fields (variables), while methods
(functions) display the object's behavior.
• Invoke a method on an object:- asking the object to perform an
action.
• In real-world object and software object have conceptually similar
characteristics.
• In terms of object-oriented programming, software objects also have a
state and behavior. 8
Object

Pen Board Laptop

Bench Projector Bike

Physical objects…
9
What is object (cont’d……….)

Result Bank Account

Logical objects…

10
Attributes and Methods of an Object

Bank Account

Object: Person Object: Car Object: Account

Attributes Attributes Attributes


Name Company AccountNo
Age Color HolderName
Weight Fuel type AccountType
Methods Methods Methods
Eat Start Deposit
Sleep Drive Withdraw
Walk Stop Transfer
11
Understand the concept of Java Classes and Objects with an example.

• You need to model real-life beings, i.e., dogs into


software entities.

12
see the picture of three different breeds of
dogs below.

13
Some of the differences maybe breed, age, size, color, etc. If you
think for a minute, these differences are also some common
characteristics shared by these dogs. These characteristics (breed,
age, size, color) can form a data members for your object

14
 Next, list out the common behaviors of these dogs like sleep,
sit, eat, etc. So these will be the actions of our software objects.

15
 So far we have defined following things,
Class – Dogs
Data members – size, age, color, breed, etc.
Methods– eat, sleep, sit and run.

16
 Now, for different values of data members (breed size, age,
and color) in Java class, you will get different dog objects.

17
How to declare / write class ?

How to create an object


(instance/variable of class)?

How to access class members ?

18
How to declare / write class
Syntax: class <class_name>{
data member;
method;
}

Class Dog

class Dog { Attributes


private: breed;
String breed; size;
String size; int age;
int age; color;
String color; Methods
void eat(); eat;
void sleep(); Sleep
void run(); }; Run;
19
Rules for Java Class

 A class can have only public or default(no


modifier) access specifier.
 It must have the class keyword, and class must be
followed by a legal identifier.
 It may optionally extend only one parent class. By
default, it extends Object class.
 The variables and methods are declared within a set of
curly braces.
 A Java class can contains fields, methods, constructors,
and blocks.

20
Creating Object & Accessing members
 Syntax: to createsnew object
ClassName objName = new ClassName();
 Example :
Dog d1= new Dog();
 Here, className is the name of class that can be anything like: Dog
that we declared in the above example.
 variable_name (d1) is name of reference variable that is used to hold
the reference of created object.
 The new is a keyword which is used to allocate memory for the object.
 Here, d1 is an object that represents the class Dog during runtime.
 Object variables and methods can be accessed using the dot (.)
operator
 Objectname.datamemeber /// to access the data member
 Objectname.method // to access the method
See next example: 21
Creating Object & Accessing members cont..d

Object
Class
class Dog { Public static void
private: main(String args[])
String breed;
{
String size;
Dog d1=new Dog();
int age;
//object
String color;
void eat(); d1.eat();
void sleep(); d1.sleep();
void run(); }; d1.run();
} } 22
Instantiating and Using Objects
 Printing to the Console
• Printing to the console refers to writing the output of a Java
program to the console.
• The methods used for streaming output are defined in the
PrintStream class. The methods used for writing console output are
print(), println() and write().
 Methods and Messages
 Methods in Java determine the messages an object can receive.
 Messages are the means by which objects interact.
 Sending a message to an object means asking the object to execute
or invoke one of its methods.
ReturnType methodName( /* Argument list */ ) {
/* Method body */
} 23
Instance fields
• say that class attributes are fields within a class:
public class Dog{
// Instance fields
String breed;
String size;
String color; }

Accessing Attributes
• You can access attributes by creating an object of the class, and by using the dot
syntax (.):
• The following example will create an object of the Dog class, with the name d1.
We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
public class Dog {
string color = “red”;
public static void main(String[] args) {
Dog d1= new Dog();
System.out.println(my Dog .color); }} 24
package classobject; ClassObject maltese = new ClassObject();
maltese.breed="Maltese";
public class ClassObject { maltese.size="Small";
maltese.age=2;
// Instance Variables
maltese.color="white";
String breed;
String size;
System.out.println(maltese.getInfo());
int age;
String color; }
// method 1 }
public String getInfo() {
return ("Breed is: "+breed+" \n
Size is:"+size+" \n Age is:"+age+"
color is: "+color);

public static void main(String[] 25


Simple Example of Object and Class
public class Student{
String name; public static void main(String[]
args) {
int rollno; Student student = new Student();
int age;
// Accessing and property value
void info(){ student.name = “abebe";
System.out.println("Name: "+name); student.rollno = 253;
System.out.println("Roll Number: student.age = 25;
"+rollno);
// Calling method
System.out.println("Age: "+age);
} student.info();//Access Methods
With an Object

}}
26
The this keyword
• this keyword in Java represents the current
instance of a class.
• Whenever the formal parameters and data members of the
class are similar, to differentiate the data members of the class
from formal parameters, the data members of class must be
proceeded by 'this'.
• With the help of this keyword, you can access
methods, fields, and constructors of the same
class within the class.
• It is basically used to eliminate the confusion
between class attributes and parameters with the
same name 27
Why use this keyword in Java?

• The main aim of using this keyword is to differentiate the


formal parameter and data members of the class. If in case, the
formal parameter and data members of the class are the same,
then it leads to ambiguity.
• So, in order to differentiate between formal parameter and data
member of the class, the data member of the class must be
preceded by the “this” keyword.
• Syntax this.data member of the current class
• We can use this keyword for the following purpose.
 For referring current class instance variable, this keyword can
be used
 To invoke current class constructor, this() is used
 Accessing Method using this keyword
 Return Current Object from a Method 28
package student11;
public class Student11 {
int id;
String name;
parameter (formal arguments) and instance
void info(int id,String name){ variables are same that is why we are using
this.id = id; this keyword to distinguish between local
this.name = name; variable and instance variable.
System.out.println("my id "+id+"\n my
name"+name);}
public static void main(String[] args) {
Student11 s1 = new Student11();
Student11 s2 = new Student11();
s1.info(321,"kebede");
//s2.info(3,"almaz");
}}

29
A class can contain any of the following variable types
• Local variables . Variables defined inside
methods, constructors or blocks.
• Instance variables . Instance variables are
variables within a class but outside any
method. It is instantiated when the class is
loaded.
• Class variables . Variables declared with in a
class, outside any method, with the static
keyword.
30
• Anonymous object: an object can be created
without explicitly assigning it to a variable, if
the object does not need to be referenced later.
Eg. new Circle();

Example:
System.out.println("Area is " + new Circle(5).getArea());

31
Methods in Java

• Method describes behavior of an object.


• A method is a collection of statements that are grouped
together to perform an operation.
• methods are declared within a class, and that they are
used to perform certain actions:
• For example, if we have a class Dog, then this class should
have methods like eat(), run(), sleep() etc, which describes the
behavior of the object.
• Declaring method is similar to function.

32
Different types of methods in Java

• Talking about the different types of methods used, there are two types, which
are:
 Standard Library Methods
 User-defined Methods
Standard library methods
• The Standard library methods are built-in methods in java that are readily
available for use. These standard libraries come along with the Java Class
Library that is present in a Java archive (*.jar) file with JVM and JRE.
How to use the standard libraries?
• The file stdlib.jar holds together all standard libraries into one single file.
To access these libraries, you must add stdlib.jar to your Java classpath.
• Some examples of Standard libraries are:
 print(): This method comes under java.io.PrintSteam which helps in printing
the string that is written within the quotation.
 sqrt(): This is a method of Math class that returns the square root of that
33
specific number.
How to create a method?
• A method must be declared within a specific class. It is defined with the
name of the method, followed by parentheses “()”. Java provides some
pre-defined methods, such as System.out.println() and many more.
• Syntax
public int methodName(int x, int y)
{
// body
}
• The above code can be broken down into:
 public static − access modifier
 int − return type
 methodName − name of the method
 x, y − formal parameters
 int x, int y − list of parameters 34
Example
String getName(String st)
{
String department=“CS";
name=name+st;
return name;
}
Calling a Method
• Methods are called to perform the functionality implemented in it.
• To call a method in Java, write the method's name and store the
returned value into a variable followed by two parentheses () and a
semicolon;
Syntax objectname. Methodname();
getName(); //Access Methods With an Object
35
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}}
In the following example, myMethod() is used
to print a text (the action), when it is called:

36
Parameter Vs. Argument in a Method

• Parameter is variable defined by a method that receives value when


the method is called.
• Parameter are always local to the method they don’t have scope
outside the method.
• argument is a value that is passed to a method when it is called.
• You can understand it by the below image that explain parameter
and argument using a program example.

37
call-by-value and call-by-reference

• There are two ways to pass an argument to a method


• call-by-value : In this approach copy of an argument value
is pass to a method. Changes made to the argument value
inside the method will have no effect on the arguments.
• call-by-reference : In this reference of an argument is pass
to a method. Any changes made inside the method will
affect the agrument value.
• NOTE :However there is no concept of call-by-reference in
Java. Java supports only call by value.

38
Method Overloading(chapter 3)
public class OverloadingMethods {
• Overloading allows public static void main(String[] ar) {
int ans1 = sum(5,2); // will return 7
different methods to int ans2 = sum(5,2,6); // will return 13
have same name, but double ans3 = sum(5.8,6.4); // will
return 12.2
different signatures. // print ans1,ans2,ans3 in order to see
• Signature can differ the result
}
by number of input // Overloaded sum(). This sum takes two int
parameters or type of parameters
public static int sum(int x, int y) {
input parameters or return (x + y);
both. }
// Overloaded sum(). This sum takes three
• Overloading is related int parameters
public static int sum(int x, int y, int z) {
to compile time (or return (x + y + z);
static) polymorphism. }
// Overloaded sum(). This sum takes two
double parameters
public static double sum(double x, double y)
{
return (x + y); 39
}}
Constructors in Java

 A constructor is a special method that is used to initialize an object.


 Every class has a constructor either implicitly or explicitly.
 Constructors are automatically called when an object is created.
 Java constructor is invoked at the time of object creation.
 It provides the values to the data members at the time of object
creation that is why it is known as constructor.
 If we don't declare a constructor in the class then JVM builds a default
constructor for that class. This is known as default constructor.
 Rules For Constructors in Java
– The name of the constructor should be the same as that of the class
name.
– A constructor cannot be declared as final, static, synchronized or
abstract.
– It cannot have an explicit return type.
– A constructor can have an access modifier to control the access
 the constructor is called when an object of a class is created. It can be
40
used to set initial values for object attributes :
Types of java constructors

• There are two types of constructors:


 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor
 A constructor that have no parameter is known as default
constructor.
 Java creates a default constructor with data members which has
values like zero, null, etc.
 Syntax of default constructor: <class_name>()
 { code…}
Example of default constructor
class defualtC{
defualtC( ) {//creating the constructor
System.out.println( 'hello learner') }
public static void main(String args[]) {
defualtC ob1 = new defualtC( )
41
}}
Parametrized Constructor

• A constructor which has arguments is called as a parametrized


constructor.
• It is used to assign values to distinct objects.
class ParameterizedC {
string name, course;
//creating a parametrized constructor
ParameterizedC(string s , string n ) {
name = s ;
course = n;
}
void show( )
{ System.out.println( name+ " " + course); }
public static void main(String args[]) {
ParameterizedC ob1 = new ParameterizedC("Java" , "J2EE");
ParameterizedC ob2 = new ParameterizedC(‘oop" , “oop with Java");
ob1.show( );
ob1.show( ); 42
Constructor Overloading

• Just like method overloading, constructors can be overloaded to


create objects in different ways.
• The compiler differentiates constructors based on how many
arguments are present in the constructor and other parameters like
the order in which the arguments are passed.
Difference Between Method And Constructor
Method Constructor
•Method name need not be •Constructor name has to be
same as the class name same as the class name

•Method has a return type •Constructor does not have a


return type
•You can call a method any •Constructor is called when an
number of times object is created 43
example
void display(){
public class Rectangle{
System.out.println("Length-" +
int length;
length + "Breadth-" + breadth+
int breadth;
"Color" + color);
String color;
}
//constructor 1
public static void main(String args[]){
Rectangle( int l , int b){
Rectangle obj1 = new
length = l;
Rectangle(2,4);
breadth = b;
Rectangle obj2 = new
color = "Green";
Rectangle(2,4,"Green");
}}
obj1.display();
//constructor 2
obj2.display();
Rectangle(int l, int b, String c){
}
length = l;
breadth = b;
color = c;
44
}
Access Modifiers in Java

• Access modifiers are keywords in Java that are used to set accessibility.
• The job of access specifier is to specify the scope of a variable (data
member), function (method), constructor or any class
• An access modifier restricts the access of a class, constructor, data
member and method in another class.
• Java language has four access modifier to control access level for classes
and its members.(public, default, protected, private)
For classes, you can use either public or default:

Modifier Description
public The class is accessible by any other class

default The class is only accessible by classes in the same


package. This is used when you don't specify a
modifier. 45
For attributes, methods and constructors, you can
use the one of the following:

Modifier Description
public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This


is used when you don't specify a modifier.

protected The code is accessible in the same package


and subclasses.

46
Public Access Modifier

• public access modifier is used to set public accessibility to a


variable, method or a class.
• Any variable or method which is declared as public can be
accessible from anywhere in the application.
• Example:
• Here, we have two class Demo and Test located in two different
package.
• Now we want to access show method of Demo class from Test
class. The method has public accessibility so it works fine. See
the below example.

47
Demo.java Test.java
• package package1; • package package2;
public class Demo
• import package1.Demo; public
• { int a = 10; // public
access modifier public class Test {
void show() • public static void main(String[] args) {
{ System.out.println(a);
Demo demo = new Demo();
}}
demo.show(); } }

48
Private Access Modifier

• Private modifier is most restricted modifier which allows


accessibility within same class only.
• We can set this modifier to any variable, method or even
constructor as well.
• Example:
• In this example, we set private modifier to show() method and try
to access that method from outside the class. Java does not allow to
access it from outside the class.
• Demo.java
Test.java
class Demo { public class Test {
int a = 10; public static void main(String[] args) {
private void show() { Demo demo = new Demo();
demo.show(); // compile error
System.out.println(a); }
}} }
49
Protected Access Modifier
• The protected access modifier is accessible within package and
outside the package but through inheritance only.
• The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
• example, Test class is extended by Demo and called a protected
method show() which is accessible now due to
inheritance.Demo.java
package package1; Test.java
package package2;
public class Demo { import package1.Demo;
int a = 10; public class Test extends Demo{

// public access modifier public static void main(String[] args) {


protected void show() { Test test = new Test();
System.out.println(a); test.show();
}
}} } 50
Non-access Modifier
• Along with access modifiers, Java provides non-access modifiers
as well.
• These modifier are used to set special properties to the variable
or method.
• Non-access modifiers do not change the accessibility of variable
or method, but they provide special properties to them.
• Java provides following non-access modifiers
– Final
– Static
Final Modifier:
 Final modifier can be used with variable, method and class.
 if variable is declared final then we cannot change its value.
 If method is declared final then it can not be overridden and
51
 if a class is declared final then we can not inherit it.
Static modifier:
• A static method can be accessed without creating an object
of the class first.
• The static can be:
– variable (also known as class variable)
– method (also known as class method)
– block
– nested class

52
Java static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc

class Employee
{
public static void main( String[] args )
int eid; {
String name; Employee se1 = new Employee();
se1.eid = 104;
static String Dept = “CS";
se1.name = “ayishu";
public void show() { se1.show();
System.out.println(eid + "-" + Employee se2 = new Employee();
se2.eid = 108;
name + "-" + Dept);
se2.name = “hana";
} se2.show();
}} 53
Java static method
• If you apply static keyword with any method, it is known as static
method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an
instance of a class.
 static method can access static data member and can change the
value of it.
// Main method
public static void main(String[ ] args)
public class Main { {
// Static method // Call the static method
static void myStaticMethod() { myStaticMethod();
System.out.println("Static methods can be called // myPublicMethod(); This would
without creating objects"); output an error
} Main myObj = new Main();
// Public method // Create an object of Main
public void myPublicMethod() { myObj.myPublicMethod();
System.out.println("Public methods must be called by // Call the public method
creating objects"); }}
} 54
• Q) why java main method is static?
• because object is not required to call static method if it
were non-static method, jvm create object first then call
main() method that will lead the problem of extra memory
allocation.

55
Encapsulation in Java

• Encapsulation in java is a process of wrapping code and


data together into a single unit,
• for example capsule i.e. mixed of several medicines.
• To achieve Encapsulation , you must:
• declare class variables/attributes as private
• provide public get and set methods to access/view and
update/modify the value of a private variable
• The get method returns the variable value, and the set method sets
the value.
• Syntax for both is that they start with either get or set, followed by
the name of the variable, with the first letter in upper case:

56
getter and setter methods

• Getters and Setters in java are two methods used for fetching and
updating the value of a variable.
• Getter methods are concerned with fetching the updated value of a
variable, while
• a setter method is used to set or update an existing variable’s value.
• The getter and setter methods provide read-only or write-
only access to our class fields.
• With the use of getters and setters, a developer can control how
variables can be accessed and updated in a proper condition.
• Getter method is a method that allows you to access and retrieve an
instance of a private variable.
• The setter method is capable of updating or setting a private
variable instance.
• The public setXXX() and getXXX() methods provide access to the
57
class’s instance variables.
Example
package encapsulation;
public class Encapsulation {
private String name;
public String getCodeName() {
return name;
}
public void setCodeName(String name){
this.name=name ;
}
public static void main(String[] args) {
Encapsulation empOne = new Encapsulation();
empOne.setCodeName("CS");
System.out.println(empOne.getCodeName());
}
58
}
Example public void setName(String
public class EncapTest { newName) {
private String name; name = newName; }
public void setIdNum( String newId) {
private String idNum;
idNum = newId; }}
private int age; public class RunEncap { public static
public int getAge() { void main(String args[]) { EncapTest
return age; } encap = new EncapTest();
public String getName() { encap.setName("James");
return name; } encap.setAge(20);
encap.setIdNum("12343ms");
public String getIdNum() {
System.out.print("Name : " +
return idNum; } encap.getName() + " Age : " +
public void setAge( int encap.getAge()); } }
newAge) {
age = newAge;
}
59
QUESTION:
IF AN OBJECT IS ALSO A COLLECTION OF VARIABLES AND
METHODS, HOW DO THEY DIFFER FROM CLASSES?

Answer:
No memory is allocated when a class is created. Memory allocation
happens only when the actual instances of a class(the objects) are
created.

60
End of Ch.2
Questions, Ambiguities, Doubts, … ???

61

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy