0% found this document useful (0 votes)
4 views

Chapter 3 Classes&Objects Electrical Converted

Uploaded by

wendmagegn64
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 3 Classes&Objects Electrical Converted

Uploaded by

wendmagegn64
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Object Oriented Programming

Computer Engineering
Department AASTU
November, 2021
Chapter 3
Classes and Objects

2
Objectives
In this chapter you will learn:
 What classes, objects, methods and instance variables are.
 How to declare a class and use it to create an object.
 How to declare methods in a class to implement the class’s
behaviors.
 How to declare instance variables in a class to implement the
class’s attributes.
 How to call an object’s method to make that method perform
its task.
 How to use a constructor to ensure that an object’s data is
initialized when the object is created.

3
Content
Classes and Objects
Access Control (private, protected, public)
Attributes and methods
Constructors

4
Classes and Objects
 Object-oriented programming (OOP)
programming using objects.
involves
 The two most important concepts in object-
oriented programming are the class and the object.
 Object
 is an entity, both tangible and intangible, in the real world that
can be distinctly identified. E.g. Student, Room, Account
 An object is comprised of data and operations
that
manipulate these data.
 E.g.1 For a Student object
 Data(property/ name, gender, birth date,
address, phone number, age,
attribute): …
home
 And operations for assigning and changing these data
values.
5
Classes and Objects(cont’d)
 E.g. 2 dog,
 data - name, breed, color, …
 behavior(operation) - barking, wagging, running.

 Class
 A class is a template or blue print that defines what an object’s
data fields and methods will be.
 For the computer to be able to create an object, we must
provide a definition, called a class.
 A class is a kind of mold or template that dictates what objects
can and cannot do.
 An object is called an instance of a class.
 Once a class is defined, we can create as many instances of
the class as a program requires. Creating an instance is
referred to as instantiation.

6
Example: Class and object

7
Declaring Class
 Class Declaration syntax
class ClassName {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
} 8
Creating Objects
 A class provides the blue print for objects; you create an
object from a class.
 Syntax:
 ClassName objectname; //object declaration
 objectname=new ClassName (parameters); // object creation
Or
ClassName objectname=new ClassName
(parameters);
 E.g. If we have the following class definition for customer:
class Customer{
//variables
public void printCust(){
//method definition
}
}
we can create “cust” objcte as follows: 9
Accessing data members
 To access data members, and methods of the class,
we use dot(.) operator.
 Objectname.data member//to access the data member of
the class
 Objectname.method // to access the method of the
class
 E.g. cust.printCust();

10
Example 1
public class GradeBook {
public void displayMessage() {
System.out.println (“Welcome to the Grade Book!”);
}
}
 A second class GradeBookTest uses and
executes the method declared in Gradebook class

11
Cont’d
public class GradeBookTest{
public static void main (String args[] ) {
GradeBook myGradeBook = new GradeBook();
myGradeBook.displayMessage();
}
}

12
Example 2: defining a class
for circle object
public class Circle {
Double pi=3.14;
Double rad;
Double area(){
return (pi*rad*rad)
;
}
Double circumf (){
return
(2*pi*rad);
}
} 13
Cont’d
public class TestCircle {
public static void main(String args[]){
Circle c1=new Circle();
c1.rad=3.0;
System.out.println (“area of the circle is:”+c1.area());
System.out.println (“circumference of the circle
is:”+c1.circumf ());
}
}

14
Access control
 Java provides a number of access modifiers to set
access levels for classes, variables, methods, and
constructors.
 The access modifiers are: private, protected,
public and default
 Access to class members (in class C in package P)
 public: accessible anywhere C is accessible
 protected: accessible in P and to any of C’s subclasses
 private: only accessible within class C
 If you don't use any modifier: only accessible in P (the default)

15
Access control(cont’d)

16
Example
// public vs private access.
class MyClass {
private int alpha; // private access
public int beta; // public access
public int gamma; // public access
//Methods to access alpha. It is
OK for a member of a class to
//access a private member of the same
class. void setAlpha(int a) {
alpha = a;
}
int getAlpha() {
return alpha;
}

17
Example(cont’d)
class AccessDemo {
public static void main(String args[]) {
MyClass ob = new MyClass();
//Access to alpha is allowed only through its accessor
//method.
ob.setAlpha(-99);
System.out.println("ob.alpha is " + ob.getAlpha());
// You cannot access alpha like this:
// ob.alpha = 10; // Wrong! alpha is private!
// These are OK because beta and gamma are
public.
ob.beta = 88;
ob.gamma = 99;
System.out.println("ob.beta is " + ob.beta);
System.out.println("ob.gamma is " +
ob.gamma);

} 18
Exercise
 Based on the following sample code and information, identify the
correct statements from a-d
ClassA{
int a;
public int b;
private int c;
protected int d;
….
}
 ClassA & ClassB are defined under package1, Class C is defined
under
Package2 and ClassD, which is sub class of ClassB, is defined under Package3
 (a) ClassB{ClassA ca = new ClassA; ca.a; }
 (b) ClassC{ClassA cb = new ClassA; cb.b;}
 (c) ClassD{ClassA cc = new ClassA; cc.c ;}
 (d) ClassD{ClassA cd = new ClassA; cd.d }
19
Local, instance and class
(static) variables
 Local variables:
 Variables defined inside methods, constructors or blocks are
called local variables.
 The variable will be declared and initialized within the method
and the variable will be destroyed when the method has
completed.
 Local variables are visible only within the declared method,
constructor or block.
 There is no default value for local variables so local variables
should be declared and an initial value should be assigned
before the first use.
 E.g. in the next slide age is a local variable. This is defined
inside pupAge() method and its scope is limited to this method
only.

20
Example: Local Variables
public class TestLocal{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.pr
intln("Puppy
age is : " +
age);
}
public static void main(String args[]){
TestLocal test = new TestLocal();
test.pupAge();
}
}
Output
21
Example(cont’d)
 Following example uses age without initializing it, so it
would give an error at the time of compilation.
public class
Test{ public void
pupAge(){
int age;
age = age + 7;
System.out.println("P
uppy age is : " +
age);
}
public static void
main(String args[]){
Test test = new Test();
test.pupAge(); 22
Instance Variables
 Are variables within a class but outside any method.
 Instance variables are created when an object
created
is with the use of the keyword 'new' and
destroyed when the object is destroyed.
 Instance variables can be declared in class
level
 before or after use.
Instance variables can be accessed directly by
calling the variable name inside the class.
However within static methods and different class
should be called using the fully qualified name.
 E. g. ObjectName.variable

23
Instance Variables(cont’d)
 Access modifiers can be given for instance variables.
 Instance variables have default values. For numbers
the default value is 0, for Booleans it is false and for
object references it is null.
 Values can be assigned during the declaration or
within the constructor.

24
Example1
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class
only. private double salary;
// The name variable is assigned a value.
public void setName(String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name :"+
name ); System.out.println("salary :" +
2
salary);
Example1(cont’d)
public static void main(String args[])
{ Employee empOne = new
Employee(); Employee empTwo =
new Employee();
empOne.setName("John");
empTwo.setName("Max");
empOne.setSalary(1000);
empTwo.setSalary(2000);
empOne.printEmp();
empTwo.printEmp();
}
}
Output:
name : John
salary :1000
.0 name : 2
Example2
public class Bank {
int balance;
void setbalance(int bal){
balance=bal;
}
int deposite( int dep)
{ balance=balance +
dep; return balance;
}
int withdraw(int withd)
{ balance=balance -
withd; return balance;
}
}
27
Example2(cont’d)
public class Runbank {
public static void main(String arg[]){
Bank cust1= new
Bank();
cust1.setbalance(1000);
System.out.println("customer 1 balance after withdrawal
"+ cust1.withdraw(300));
System.out.println(" Customer 1 balance after depositing
"+ cust1.deposite(3000));
Bank cust2= new Bank();
cust2.setbalance(5000);
System.out.println(" customer 2 balance after withdrawal
"+ cust2.withdraw(500));
System.out.print(" customer 2 balance after depositing

"+
cust2.deposite(3000)); 28
Example 3: Predict output
public class Foo
{ private boolean
x;
public static void main(String[] args)
{ Foo foo = new Foo();
System.out.println(foo.x);
}
}

29
Class/static variables
 Class variables also known as static variables are
declared with the static keyword in a class, but outside
a method, constructor or a block.
 Every object has its own copy of all the instance
variables of the class. But, there would only be one
copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than
declared as constants. Constant variables being
change from their initial value. never
 Static variables are created when the program starts and
destroyed when the program stops.
 Default values are same as instance variables.
30
Example1
public class Employee2{
// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
public static String DEPARTMENT = "Development ";

public static void main(String args[]){


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" +
salary);
}
}

31
Example 2
public class Employee3 {
// this instance variable is visible for any child class.
public String name;
public static double initialsalary;
// The name variable is assigned in the constructor.
public Employee3 (String empName){
name = empName;
}
// The salary variable is assigned a
value. public void setSalary(double
empSal){
initialsalary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("initial salary :" +
initialsalary);
} 32
Example2(cont’d)
public class EmployeeTest{
public static void main(String args[]){
Employee3 empOne = new
Employee3(“Ahmed"); empOne.setSalary(1000);
empOne.printEmp();
Employee3 emptwo = new Employee3(“Kedir");
/* here the initial salary for the second employee
emptwo.setSalary(xxx) is not set hence it uses the one
that is set by the first object since only one copy of the
initial salary exist */
emptwo.printEmp();
}
}

33
Example 3: Predict output
class Counter{
int count=0;// what if it is static int count=0;
public void printCounter()
{ count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
c1.printCounter();
Counter c2=new Counter();
c2.printCounter();
Counter c3=new Counter();
c3.printCounter();
}
}

34
Methods
 Method describe behavior of an object.
 A method is a collection of statements that are
group together to perform an operation.
 Java methods are like C/C++ functions. General
case:
[modifier] returnType methodName ( arg1, arg2, … argN)
{
methodBody
}
 Example:

35
Instance and Static Methods
 Methods are defined in a class, invoked using the class object.
 Normally a class member must be accessed only in conjunction with an
object of its class. There will be times when you will want to define a class
member that will be used independently of any object of that class.
 It is possible to create a member that can be used by itself, without
reference to a specific instance. To create such a member, precede its
declaration with the keyword static.
 When a member is declared static, it can be accessed before
any
objects of its class are created, and without reference to any object.
 The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.

36
Instance and Static Methods(cont’d)
Class methods Instance Methods
Static methods are declared by using static instance methods are declared without static
keyword. keyword
All objects share the single copy of static All objects have their own copy of instance
method. method.
Static method does not depend on the single Instance method depends on the object for
object because it belongs to a class which it is available.
Static method can be invoked without creating Instance method cannot be invoked without
an object, by using class name. creating an object.
ClassName.method( ); ObjectName.method( );

Static methods cannot call non-static methods. Non-static methods can call static methods
Static methods cannot access non-static Non-static methods can access static variables
variables.
Static methods cannot refer to this or super. Instance methods can refer to this and super

37
Example
 Suppose that the class Foo is defined in (a). Let f be an instance of Foo.
Which of the statements in (b) are correct?
 (a)
public class Foo {
int i;
static String s;
void imethod() {
}
static void
smethod() {
}
}
(b)
System.out.println(f.i);
System.out.println(f.s);
f.imethod();
f.smethod();
System.out.println(Foo.i);
System.out.println(Foo.s);
3
Foo.imethod();
Example 2
public class EmployeeStatic{
private String firstName;
private String lastName;
private static int count = 0; // number of objects in memory
public EmployeeStatic( String first, String last ) {
firstName = first;
lastName = last;
count++;
System.out.println
( "Employee
constructor:" +
firstName +
lastName
+";count= " +
count );
} 39
Example 2(cont’d)
public String getLastName(){
return lastName;
} // end method getLastName
public static int getCount()
{
return count;
}
}

40
Example 2(cont’d)
public class EmployeeStaticTest{
public static void main( String args[] ) {
// show that count is 0 before creating Employees
System.out.println( "Employees before instantiation: " +
EmployeeStatic.getCount());
// create two Employees; count should be 2
EmployeeStatic e1 = new EmployeeStatic( "Susan",
"Baker" ); EmployeeStatic e2 = new EmployeeStatic( "Bob",
"Blue" );

// show that count is 2 after creating two Employees


System.out.println( "\nEmployees after instantiation: " );
System.out.println( "via e1.getCount():" +e1.getCount() );
System.out.println( "via e2.getCount():" + e2.getCount());
System.out.println( "via Employee.getCount():"+
EmployeeStatic.getCount());

41
Example 2(cont’d)
// get names of Employees
System.out.println( "Employee 1: "+ e1.getFirstName()+ " " +
e1.getLastName());
System.out.println( "Employee 2: "+ e2.getFirstName()+ " "
+ e2.getLastName());
} // end main
} // end class EmployeeStaticTest

42
Declaring a method with a
parameter
 A method can require one or more parameters that
represent additional information it needs to perform
its task.
 A method call supplies values—called arguments—for
each of the method’s parameters.
 For example, to make a deposit into a bank account,
a deposit method specifies a parameter that
represents the deposit amount.

43
Example
public class GradeBook2{
public void displayMessage(String courseName){
System.out.print( "Welcome to the grade book for"+ courseName );
}
}
import java.util.*;
public class GradeBookTest2 {
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
GradeBook2 myGradeBook = new GradeBook2();
System.out.print( "enter the course name” );
String nameOfCourse = input.nextLine();
myGradeBook.displayMessage( nameOfCourse )
;
}} 4
Constructors
 Constructor in java is a special type of method that
is used to create or construct instances of the class.
 Called when keyword new is followed by the class
name and parentheses
 Their name is the same as the class name
 It looks like a method, however it is not a method.
Methods have return type but constructors don’t have
any return type(even void).
 Format: public ClassName(para){…}
 A constructor with no parameters is referred to as
a
no-arg constructor. 45
Default Constructor
 A class may be declared without constructors.
 In this case, a no-arg constructor with an empty body
is implicitly declared in the class. This constructor,
called a default constructor, is provided
automatically only if no constructors are explicitly
declared in the class.
 Format: public ClassName(){…}

46
Constructor Example

public class EmployeeConstructor{


// this instance variable is visible for any child
class. public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public EmployeeConstructor (String empName){
name = empName;
}
// The salary variable is assigned a
value. public void setSalary(double
empSal){
salary = empSal;
}
47
Constructor example(cont’d)
// This method prints the employee details.
public void printEmp()
{ System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
EmployeeConstructor empOne = new
EmployeeConstructor(“Leta");
empOne.setSalary(1000);
empOne.printEmp();
}
}

48
Example 2
class Account {
// Data Members
private double balance;
//Constructor
public Account(double startingBalance) {
balance = startingBalance;
}
//Adds the passed amount to the balance
public void depos(double amt) {
balance = balance + amt;
}
//Returns the current balance of this account
public double getCurrentBalance( ) {
return balance;
}
}
49
Example2(cont’d)
import java.util.Scanner;
public class AccountTest{
public static void main(String args[])
{ Scanner in = new
Scanner(System.in); Double bal, amt;
Account acct = new Account(200);
System.out.println("Please enter amount of deposit");
amt= in.nextDouble();
acct.depost (amt);
System.out.println("The current balance is: " +
acct.getCurrentBalance());

}
}

50
Exercise
 Which of the following constructors are invalid?
1. public int ClassA(int one) {
...
}
2. public ClassB(int one, int two) {
...
}
3. void ClassC( ) {
...
}

51
Multiple constructors
 A class can have multiple constructors, as long as
their signature (the parameters they take) are not the
same.
 You can define as many constructors as you need.

52
Example
public class CircleConstructor {
public double r; //instance variable
// Constructors
public CircleConstructor(double radius)
{ r = radius;
}
public CircleConstructor()
{ r=1.0;
}
//Methods to return
area public double
area() {
return 3.14 * r * r;
}
} 53
Example(cont’d)
public class CircleConstructorTest{
public static void main(String args[]){
CircleConstructor circleA = new CircleConstructor(20.0);
CircleConstructor circleB = new
CircleConstructor(10.0); CircleConstructor circleC =
new CircleConstructor();
Double ca =
circleA.area();
System.out.println(ca);
Double cb =
circleB.area();
System.out.println(cb);
Double cc =
circleC.area();
System.out.println(cc);
}
54
}
Accessors and mutators
 A class’s private fields can be manipulated only by
methods of that class.
 Classes often provide public methods to allow clients
of the class to set (i.e., assign values to) or get (i.e.,
obtain the values of) private instance variables.
 Set methods are also commonly called mutator
methods, because they typically change a value. Get
methods are also commonly called accessor
methods or query methods

55
Example
class Person{
private String fname;
private String mname;
private String lname;
private String addr;
public Person(String

firstname, String
middlename, String

lastname,
String address){// constructor
fname=firstname;
mname=middlename;
lname=lastname;
addr=address;
}
public String getFname(){ // accessor for fname
return fname;
} 56
Example(cont’d)
public String getLname(){ // acccessor for Lname
return lname;
}
public String getAddress(){ // accessor for Address
return addr;
}
public void setAddress(String address){ //mutator for
address
addr=address;
}
public void setLname(String lastname){ //mutator for Last name
lname=lastname;
}
}

57
Example(cont’d)
public class PersonExample{
public static void main(String args[]){
Person dani=new Person("Daniel","Abebe", “Kebede", “Adama");
System .out.println(dani.getFname()+" "+dani.getMname()+"
"+dani.getLname()+ " "+dani.getAddress() );
dani.setAddress("Addis Ababa"); //to change Adama to Addis
Ababa
though address is private
dani.setLname(“Kebede");//to change last name from
Kebede to Leta although private
System .out.println(dani.getFname()+" "+dani.getMname()+"
"+dani.getLname()+ " "+dani.getAddress() );
}
}

58
Box Example
// Use this to resolve name-space
collisions.
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() {
return width * height * depth; 59
Box Example(cont’d)
class BoxDemo{
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first
box vol =
mybox1.volume();
System.out.println("Vol
ume is " + vol);
// get volume of second
box vol =
mybox2.volume();
System.out.println("Volum 60
The this Keyword
 is used to refer always current object/current instance
of a class
(I) Instance Variable Hiding
 It is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.
 when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
 The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables
and parameters, this keyword resolves the problem of
ambiguity.

61
Example
// Use this to resolve name-space collisions.
class Box
{ double
width; double
height;
double depth;
// This is the
constructor
for Box.
Box(double width, double height, double depth)
{ this.width = width;
this.height = height;
this.depth = depth;
}
// compute and return volume
double volume() {
return width * height * depth;
} 62
Example(cont’d)
class BoxDemo{
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first
box vol =
mybox1.volume();
System.out.println("Vol
ume is " + vol);
// get volume of second
box vol =
mybox2.volume();
System.out.println("Volum 63
The this Keyword(cont’d)
 (II) to invoke current class method

64
The this Keyword(cont’d)
 (III) To call another overloaded Constructor
 “this” keyword can be used inside the constructor to
call another overloaded constructor in the same Class.
 Example
class JBT {
JBT() {
this("JBT");
System.out
.println("In
side
Constructo
r without
parameter
");
}
JBT(String
str) {
System.out.p
rintln("Inside 65
Example: predict output
public class Officer{
public Officer(){
this("Second");
System.out.println("I am First");
}
public Officer(String name){
System.out.println("Officer
name is " + name);
}
public Officer(int salary){
this();
System.out.println("Officer
salary is Rs." + salary);
}
public static void main(String
args[]){ 6
Exercise
 Define a class product with members(name, price, qty &
calcCost(),calcTax())
 Input values
 Using constructor
 Using input from keyboard(Scanner/JOptionPane)
 What if for N-products

 Define four static methods of


simple calculator(Arithemetic)
 Input values
 Using constructor
 Using input from
keyboard(Scanner/JOptionPane)

6
3.6 Packages
• Packages in Java are a way of grouping similar types of
classes / interfaces together.(acts as a container for group
of related classes).
• It is a great way to achieve reusability.
• We can simply import a class providing the required
functionality from an existing package and use it in our
program.
• it avoids name conflicts and controls access of class, interface and
enumeration etc
• It is easier to locate the related classes
• The concept of package can be considered as means to achieve data
encapsulation.
• consists of a lot of classes but only few needs to be exposed as most
of them are required internally. Thus, we can hide the classes and
prevent programs or other packages from accessing classes which
are meant for internal usage only.68
Cont…
 The Packages are categorized as :

 Built-in packages ( standard packages which come


as a
part of Java Runtime Environment )
 These packages consists of a large number of classes
which are a part of Java API
 Accessing classes in a package: Eg:-
1 ) import java.util.Random; // import the Random class
from util package

2 ) import java.util.*; // import all the class from util


package
 User-defined packages ( packages
defined by
programmers to bundle group of related classes
)
 Java is a friendly language and permits to create our own packages
and use in programming. 69
Built-in packages
 Examples:
Package Name Description
Contains language support classes ( for
e.g classes which defines primitive
java.lang
data types, math operations, etc.) .
This package is automatically
imported.
Contains classes for supporting input /
java.io
output operations.
Contains utility classes which
implement data structures like Linked
java.util
List, Hash Table, Dictionary, etc and
support for Date / Time operations.

java.applet Contains classes for creating Applets.


Contains classes for implementing the
java.awt components of graphical user interface
( like buttons, menus, etc. ).
Contains classes for supporting
java.net
networking operations.
70
User defined packages
 Creating a package in java is quite easy.
 Simply include a package command followed by
name of the package as the first statement in java
source file.
 package RelationEg;

 However, because of new editors we can simply


create using GUI wizard
 R->click on ur project
 New java-package
 Then you can create many-related classes in it

71
package REL1;
public class Comp1 {
public int getMax(int x, int y)
{ if ( x > y ) {
return x;
}
else {
return y;
}
}
}

72
package packageeg;
import REL1.Comp1;
public class EgComp {
public static void main(String args[]) {
int val1 = 7, val2 = 9;
Comp1 comp = new Comp1();
int max = comp.getMax(val1, val2); // get the max value
System.out.println("Maximum value is " + max);
}
}

73
Questions
 Can we make a class private? If no which specific
access modifiers can be used with class.
 If we define class with protected access modifier can
we create public method?
 Double vs. double
 Is an array an object or a primitive type value?

74

You might also like