OOP Chap 2 Deber Markose
OOP Chap 2 Deber Markose
Burie Campus
Department of Computer Science
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
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
Physical objects…
9
What is object (cont’d……….)
Logical objects…
10
Attributes and Methods of an Object
Bank Account
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 ?
18
How to declare / write class
Syntax: class <class_name>{
data member;
method;
}
Class Dog
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);
}}
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?
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
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
37
call-by-value and call-by-reference
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
• 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
Modifier Description
public The code is accessible for all classes
46
Public Access Modifier
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
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
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