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

Chapter Two: 2. The Inside of Objects and Classes: More OOP Concepts

This document discusses object-oriented programming concepts like classes, objects, constructors, and methods. It explains that classes define the structure and behavior of objects, and that objects are instantiated from classes using the new keyword. Constructors initialize objects, and can be default, parameterized, or overloaded. Methods allow modularization by separating tasks into self-contained units, and can return values or not. Access specifiers like public, private, and protected control method accessibility.

Uploaded by

Fetene Belete
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Chapter Two: 2. The Inside of Objects and Classes: More OOP Concepts

This document discusses object-oriented programming concepts like classes, objects, constructors, and methods. It explains that classes define the structure and behavior of objects, and that objects are instantiated from classes using the new keyword. Constructors initialize objects, and can be default, parameterized, or overloaded. Methods allow modularization by separating tasks into self-contained units, and can return values or not. Access specifiers like public, private, and protected control method accessibility.

Uploaded by

Fetene Belete
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter Two Object Oriented Programming

Chapter Two
2. The Inside of Objects and Classes: More OOP Concepts.

2.1 Member Functions and Their Components.

Class Declaration
- Class is a java keyword and all the normal keyword restrictions apply. One
way of thinking about a java class is to note that they resemble structures. We
simply use the key word class instead of struct, and the member of the
structure become private by default.
- the class declaration syntax is:
- class class_name{
data_members;
...
class_methods();
...;
}

Instantiation & Initializing class objects.


- The process of creating an object from a class is called instantiation. To create
an object from a java class, one must use the ‘new’ keyword.

Object Creation
- No object is actually created by the declaration process. An object declaration
simply declares the name (identifier), which we use to refer to an object. eg:
- Account account; designate that the name account is used to refer to an
account object, but the actual Account object is not yet created. We create an
object by invoking the new command. the syntax is:
- <object name> = new <class name>(<arguments>);
- Where <object name> is the name of a declared object, <class name> is the
name of the class to which the object belongs, and <argument> is a sequence
of values passed to the method.
- let us see the distinction between object declaration and object
creation/instantiation

1 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

A. Account account; State of memory


after A is executed

account

The identifier account is declared and placed in


memory

2 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

Created with Created with


the first new the second new - Since
there is no reference to the first customer object anymore, it will eventually be
erased and returned to the system. Remember that when an object is created, a
certain amount of memory space is allocated for storing objects. If this allocated
but unused space is not returned to the system for other use, the space gets wasted.
This returning of space to the system is
called deallocation, and the mechanism to deallocate unused space is called
garbage collection.

3 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

Constructors
- A constructor is a special initialization method that is called automatically
whenever an instance of a class is created. The constructor member method
has, by definition, the same name as the corresponding class. The constructor
has no return value specification, not even void. The Java run-time system
makes sure that the constructor of a class is called when instantiating an
object.
- Constructors are used to initialize the data members of the class. If we have
data members that must be initialized, we must have a constructor. In our
constructor, we should not do something that might fail because; the
constructor does not return a value.

Default (Non-Parameterized) constructors


- Let us look at the following example.

public class Employee{


private String empName;
private String address;

public Employee()
{
empName = “”;
address = “”;
}
}//end class

- The constructor Employee() is a default or a non-parameterized constructor,


because it declares no parameters.

Parameterized constructors
- The parameterized constructors can accept values into the constructor that has
different parameters in the constructor. The value would be transferred from
the main() method to the constructor either with direct values or through
variables.

4 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

Using overloaded constructors


- Overloaded constructors enable object of a class to be initialized in different
ways. To overload constructors, simply provide multiple constructor
declarations with different parameter lists.
- Attempting to overload a constructor with another constructor that has the
exact same signature (name and parameters) is a syntax error.
- for instance, consider the constructors of the following class:

Public class Person{

5 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

}
}//end class

- The above class contains five overloaded constructors that provide convenient
ways to initialize objects of class person. Each constructor guarantees that
every object the constructor initializes begins in a consistent state.
- The above class uses the keyword this to call / invoke a specific constructor
with the specified number and type of argument. It is a syntax error, when the
‘this’ reference is used in a constructor’s body to call another constructor of
the same class and that statement is not the first statement in the constructor. It
is also a syntax error when a non-constructor method attempts to invoke a
constructor directly via the ‘this’ reference.

Methods
- Methods (some times called functions or procedures) allow the programmer to
modularize a program by separating its tasks into self-contained units. These
units are sometimes called programmer defined methods.

6 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

- A method is invoked or called by a method call. The method call specifies the
name of the method and provides information (arguments) that the called
method requires to perform its task. When the method call completes, the
method either returns a result to the calling method (or caller) or simply
returns the control to the caller.
- The first line of the method declaration is called the method header.
Following the method header, declaration and statements in brace form the
method body, which is a block. Variables can be declared in any block, and
blocks can be nested. A method can’t be declared inside another method.
- the basic format of a method declaration is :
- return-value-type method-name(para1,para2,...,paraN)
{
declarations and statements;
}
- The method-name is any valid identifier. The return-type is the type of the
result returned by the method to the caller. The return-type void indicates that
a method does not return a value. Methods can return at most one value.
- eg. public double maximum(double x,double y,double z)
{
return Math.max(x,Math.max(y,z));
}

Access specifiers and methods


- Access specifiers are used to restrict access to the method. Regardless of what
the access specifier is, the method is accessible from any other method in the
same class. However, although all methods in a class are accessible by all
other methods in the same class, there are certain necessary tasks that you
might not want other objects to be able to perform.
- Let us see the access specifiers of Java language; public, private and
protected.
- public: the public modifier is the most relaxed possible for a method. by
specifying a method as public, it becomes accessible to all classes regardless
of their lineage or their package;
- protected: any class that extends the current class can access protected
members. But other classes which are not related to the current class in an
inheritance can’t make use of the protected members of the current class. If
you didn’t assign a modifier in front of a class declaration, the class is created

7 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

with the default properties. By default, all classes are assigned to package
level visibility. This means that while the class may be extended and
employed by other classes, only those objects within the same package may
make use of this class.
- private: private is the highest degree of protection that can be applied to a
method. A private method is only accessible by those methods in the same
class. Even classes that extend from the current class do not have access to a
private member.
Other important concepts :
- final: final classes may not have any subclasses and are created by placing the
modifier final in front of he class declaration. A variable can be decaled as
final. Doing so prevents its contents from being modified. This means that you
must initialize a final variable when it is declared. (In this usage, final is
similar to const in C++).
- abstract: an abstract class is a class that is incomplete, or to be considered
incomplete. Only abstract classes may have an abstract method. That is,
methods that are declared but not yet implemented. If a class that is not
abstract contains an abstract method, then a compile-time error occurs. A class
has abstract methods if any of the following is true; if: it explicitly contains a
declaration of an abstract method. it inherits an abstract method from its
direct superclass.
- An abstract class is defined with the modifier abstract. No instance can be
created from an abstract class. consider the following example:

the keyword abstract public class


Student{ abstract here protected String name;
denotes an abstract protected String courseGrade;
class
public Student()
{
this(“No Name”);
}

public Student(String studName)


{
name = studName;
courseGrade = “NG”;
}
here the keyword abstract public void computeCourseGrade();
denotes an abstract
method public String getCourseGrade()
{
return courseGrade;

8 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

public String getName()


{
return name;
}
}//end class

- An abstract method is a method with the keyword abstract and it ends with a
semicolon instead of a method body. We say a method is implemented if it has
a method body.

Accessors and Mutators. / get() and set() Methods


- private fields can be manipulated only by methods of the class in which the
fields are declared. 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. These methods need not be called set and get, but they
often are. Set methods are also commonly called mutator methods (because
they typically change a value). Get methods are also commonly called
accessors or query methods.
- If an instance variable is declared public, the instance variable can be read or
written at will by any method that has reference to an object of the class in
which the instance variable is declared.
- Using a public set and get method ensures that the new value is appropriate
for that data item. For example, an attempt to set the day of the month for a
data to 37 would be rejected; an attempt to set a person’s weight to a negative
value would be rejected, and so on. So, although set and get methods could
provide access to private data, the access is restricted by the programmer’s
implementation.

Calling and returning: methods


- Generally, the calling method controls method calls and their order. The called
method is controlled by the calling method.
- Let us see an example:

public class First{


public void next_fun()
{
System.out.println(“Inside next_fun()”);
}

9 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

public void third_fun()


{
System.out.println(“inside third_fun()”);
}
}//end class

public class TestFirst{


public static void main(String args[])
{
First fr = new First();
fr.next_fun();
fr.third_fun();
System.out.println(“main() is compleated”);
}
}//end class

Passing values to methods


- Java provides two methods for passing variables between methods. We will
see passing by value and passing by address in the following section.

Passing by value
- Here, the actual variable will not be passed; rather, the value of the variable is
passed to the receiving method. Because the value/copy of the variable is
passed to the receiving method, the receiving method can’t modify the calling
method’s variable.
- Consider the following program that calculates the factorial of a give number.
The example illustrates passing by value.

import java.io.*; public


class Factorial{
public void calcFact(int n)
{
int i,fact=1;
for(int i=1;i<=n;i++)
fact*=i;
System.out.println(“the factorial of ”+n+ “is ”+fact);
}
}//end class

public class TestFactorial{


public static void main(String args[])

10 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

{
Factorial fact = new Factorial();
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String num =
input.readLine(); int n =
Integer.parseInt(num);
fact.calcFact(n); }
}//end class

Passing by address
- When we pass an argument (local variable) by address, the variable’s address
is assigned to the receiving method’s parameter. The address of the
variablenot its value is copied to the receiving method’s parameter when we
pass a variable address. In Java, all the arrays are passed by address.

Passing arrays to methods


- Java automatically passes arrays to methods using simulated call-byreference;
the called methods can modify the element values in the callers, the original
values. The value of the name of the array is the address of the first element of
the array. Because the starting address of the array is passed, the called
method knows precisely where the array is stored.
- Although entire array are passed simulated call-by-reference yet the individual
array elements are passed call-by-value, exactly as simple variables are. For a
method to receive an array through a method call, the method’s parameter list
must specify that an array would be received.
- Eg. public class ArrayEg{
public void modifyArray(int num[])
{
for(int i=0;i<num.length;i++)
num[i]+=2;
System.out.println(“inside modifyArray()”);
for(int i=0;i<num.length;i++)
System.out.println(num[i]+” ”);
}
}//end class

public class TestArray{


public static void main(String args[])
{

11 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

int a[] = new int[10];


for(int i=0;i<a.length;i++)
a[i]=i+1;
System.out.println(“inside main()”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
ArrayEg aEg = new ArrayEg();
System.out,println();
aEg.modifyArray(a);
System.out.println();
System.out.println(“back inside main()”); for(int
i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
}
}//end class

Method return values


- When we want to return a value from a method to its calling method, we put
the return value after the return statement.
- Do not return global variables. There would not be any need to do so because
their values are already known thought the code.

Static versus instance members


- Each object has its own copy of all the instance variables of a class. In certain
cases, only one copy of a particular variable should be shared by all objects of
a class. A static field-called a class variable- is used in such case, among
others. A class variable represents class-wide info- all objects of the class
share the same piece of data. The declaration of a static member begins with
the keyword static.
- Although class variables may seem like global variables, class variables have
class scope. A class’s public static member can be accessed through a
reference to any object of that class, or they can be accessed by qualifying the
member name with the class name and a dot (.), as in Math.random(). A
class’s private static class member can only be accessed through methods of
that class. Actually, static class member exist even when no object of that
class exist- they are available as soon as the class is loaded into memory at
execution time. To access a private static member when no object of the class
exist, a public static method must be provided and the method must be called
by qualifying its name with the class name and a dot. Consider the following
example.

12 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

public class Employee{


private String firstName;
private String
secondName; private static
int count1=0;
public static int count2=0;

public Employee(String fName,String sName)


{
firstName=fName;

secondName=sName;
count1++;
count2++; }

public String getFirstName()


{
Return firstName;
}

public String getSecondName()


{
Return secondName;
}

public static int getCount()


{
Return count1;
}
}//end class

public class TestStatic{


public static void main(String args[])
{
System.out.println(“using public method:”+Employee.getCount());
System.out.println(“using public var:”+Employee.count2);
Employee e2 = new Employee(“Saba”,”Getachew”);
Employee e2 = new Employee(“Zeritu”,”Kebede”);
System.out.println(“using public method:”+e1.getCount());
System.out.println(“using public var:”+e2.count2);
System.out.println(“After instantiation:”+Employee.getCount());
System.out.println(“After instantiation:”+Employee.count2);
System.out.println(“accessing instance members”);

13 Compiled By Tewodors G.
Chapter Two Object Oriented Programming

System.out.println(“employee1:”e1.getFirstName()+”
“+e1.getSecondName());
System.out.println(“employee2:”e2.getFirstName()+ “
”+e2.getSecondName());
}
}//end class

NB: A method declared static can’t access a non-static class member. Unlike nonstatic
methods, a static method has no “this” reference because static variables and static
methods exist independent of any object of a class whether or not any objects of the class
have been instantiated.

14 Compiled By Tewodors G.

You might also like