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

OOP Chapter - 2

Uploaded by

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

OOP Chapter - 2

Uploaded by

eyuel haile
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter – 4 OOP Concepts

Object & Classes

Java is an Object-Oriented Language. As a language that has the Object


Oriented feature, Java supports the following fundamental concepts:
 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
In this chapter, we will look into the concepts Classes and Objects.
 Object - Objects have states and behaviors. Example: A dog has states-
color, name, breed as well as behaviors -wagging, barking, eating. An object
is an instance of a class.
 Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can
find many objects around us, Cars, Dogs, Humans, etc. All these objects have a
state and behavior. If we consider a dog, then its state is - name, breed, color, and
the behavior is - barking, wagging, running If you compare the software object
with a real world object, they have very similar characteristics. Software objects
also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods. So in software development, methods operate on
the internal state of an object and the object- to-object communication is done via
methods.

Classes in Java:

A class is a blue print from which individual objects are created. A sample of a class
is given below:
public class
Dog{ String
breed;

int age; String


color; void
barking(){

}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
 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.
 Instance variables: Instance variables are variables within a class but
outside any method. These variables are instantiated when the class is
loaded. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
 Class variables: Class variables are variables declared within a class,
outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when
looking into classes of the Java Language.
Constructors:
When discussing about classes, one of the most important subtopic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
Example of a constructor is given below:
public class
Puppy{ public
Puppy(){

}
public Puppy(String name){
// This constructor has one parameter, name.
}
Creating an Object:

As mentioned previously, a class provides the blueprints for objects. So basically


an object is created from a class. In Java the new keyword is used to create new
objects. There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name with an object
type.
 Instantiation: The 'new' keyword is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor.
This call initializes the new object.

Example of creating an object is given below:


public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );

}
public static void main(String[]args){
// Following statement would create an object myPuppy
Puppy myPuppy =new Puppy("tommy");

}
}

If we compile and run the above program, then it would produce the following
result:

Passed Name is: tommy


Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects. To access an
instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example:

This example explains how to access instance variables and methods of a class:

public class
Puppy{ int
puppyAge;

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );

}
public void setAge(int age )
{ puppyAge = age;

}
public int getAge(){
System.out.println("Puppy's age is :"+ puppyAge );
return puppyAge;

}
public static void main(String[]args){
/* Object creation *
Puppy myPuppy =newPuppy("tommy");
/* Call class method to set puppy's age */
myPuppy.setAge(2);

/* Call another class method to get puppy's age */


myPuppy.getAge();

/* You can access instance variable as follows as well */


System.out.println("Variable Value :"+ myPuppy.puppyAge );

}
}

If we compile and run the above program, then it would produce the following
result:

PassedName is:tommy
Puppy's age is :2
Variable Value :2
Source file declaration rules:

As the last part of this section, let‘s now look into the source file declaration rules.
These rules are essential when declaring classes, import statements and package
statements in a source file.
 There can be only one public class per source file.
 A source file can have multiple nonpublic classes.
 The public class name should be the name of the source file as well which
should be appended by .java at the end. For example: The class name is.
public class Employee{} Then the source file should be as Employee.java.

 If the class is defined inside a package, then the package statement should be
the first statement in the source file.
 If import statements are present then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
 Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.

Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. I will be explaining about all these in the
access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special
classes called Inner classes and Anonymous class
1. INHERITANCE

Inheritance can be defined as the process where one object acquires the
properties of another. With the use of inheritance, the information is made
manageable in a hierarchical order. When we talk about inheritance, the
most commonly used keyword would be extends and implements. These
words would determine whether one object IS-A type of another. By using
these keywords, we can make one object acquire the properties of another
Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of parent class, and you can add new methods
and fields also.

• One of the most effective features of Oop’s paradigm.


• Establish a link/connectivity between 2 or more classes.
• Permits sharing and accessing properties from one to another class.
• to establish this relation Java uses ‘extends’ keyword.
Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be


achieved).
 For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives
from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The
new class is called a subclass.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[])
{ Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Output:

Programmer salary is:40000.0

Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as
well as of Employee class i.e. code reusability.
Category of Classes on the Basis of Inheritance
1. Super class
 (base/parent/driver/inheritance/ ancestor class).
 Top located class
 Service provider (its properties accessed by all its lower level class).

2. Intermediate class
 (mediating/dual class).
 Middle located class
 Having Dual policy (obtain properties of upper level class and transmit
properties to lower level class).

3. Child class
 (sub/associate/derived/inherited class).
 Bottom located class much benefitted class much loaded class
 properties of child class as well as
 class and parent class can be accessed by
 only the object of child class.
Relation between classes

TYPES of INHERITANCE
1. Single Inheritance
 A structure having one and only one parent as well
as child class.
 Child class is authorized to access the property of parent class
2. Multilevel Inheritance
 Standard structure of Single Inheritance having one Parent, one or
more intermediate and one child classes.
 Child class as well as intermediate class may access the properties of
upper level classes.

3. Hierarchical Inheritance
 A structure having one parent and more child class.
 Child classes must be connected with only Parent class.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another
by using the extends keyword. To see how, let’s begin with a short example. The
following program creates a superclass called A and a subclass called B. Notice
how the keyword extends is used to create a subclass of A.
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

The output from this program is shown here:


Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
As you can see, the subclass B includes all of the members of its superclass, A.
This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and
j can be referred to directly, as if they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-
alone class. Being a superclass for a subclass does not mean that the superclass
cannot be used by itself. Further, a subclass can be a superclass for another
subclass. The general form of a class declaration that inherits a superclass is shown
here: class subclass-name extends superclass-name {
// body of class
}
You can only specify one superclass for any subclass that you create. Java does not
support the inheritance of multiple super classes into a single subclass. You can, as
stated, create a hierarchy of inheritance in which a subclass becomes a superclass
of another subclass. However, no class can be a superclass of itself.
2. Polymorphism

Polymorphism is the ability of an object to take on many forms. In programming


languages polymorphism is the capability of an action or method to do different
things based on the object that it is acting upon. This is the third basic principle of
object oriented programming. The two types of polymorphism are: method
overloading and Method overriding.

Overloaded methods are methods with the same name signature but either a
different number of parameters or different types in the parameter list. For example
'spinning' a number may mean increase it, 'spinning' an image may mean rotate it
by 90 degrees. By defining a method for handling each type of parameter you
control the desired effect.

Overridden methods are methods that are redefined within an inherited or subclass.
They have the same signature and the subclass definition is used.

Casting Objects

One of the difficulties of using a superclass array to hold many instances of


subclass objects is that one can only access properties and methods that are in the
superclass (ie. common to all). By casting an individual instance to its subclass
form, one can refer to any property or method. But first take care to make sure the
cast is valid by using the instanceof operator. Then perform the cast. As an
example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object


{
Dog doggy = (Dog) ref[x]; // cast current instance to subclass
doggy.someDogOnlyMethod();
}

Casts to subclass can be done implicitely but explicit casts are recommended. Casts
to superclass must be done explicitly. Casts cannot be made between sibling
classes.
Method overloading and method overriding in Java
Method overloading and method overriding uses concept of Polymorphism in Java
where method name remains same in two classes but actual method called by JVM
depends upon object at run time and done by dynamic binding in Java. Java
supports both overloading and overriding of methods. In case of overloading
method signature changes while in case of overriding method signature remains
same and binding and invocation of method is decided on runtime based on actual
object. This facility allows Java programmer to write very flexibly and
maintainable code using interfaces without worrying about concrete
implementation. One disadvantage of using Polymorphism in code is that while
reading code you don't know the actual type which annoys while you are looking
to find bugs or trying to debug program. But if you do Java debugging in IDE you
will definitely be able to see the actual object and the method call and variable
associated with it.
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within a subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden.
Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined
within B is used. That is, the version of show( ) inside B overrides the version
declared in A. If you wish to access the superclass version of an overridden
method, you can do so by using super. For example, in this version of B, the
superclass version of show( ) is invoked within the subclass’ version. This allows
all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the
following
output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).
Method overriding occurs only when the names and the type signatures of the two
methods are identical. If they are not, then the two methods are simply overloaded.
For example, consider this modified version of the preceding example:
// Methods with differing type signatures are overloaded – not
// overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B

subOb.show(); // this calls show() in A


}
}
The output produced by this program is shown here:
This is k: 3
i and j: 1 2
The version of show( ) in B takes a string parameter. This makes its type signature
different from the one in A, which takes no parameters. Therefore, no overriding
(or name hiding) takes place. Instead, the version of show( ) in B simply overloads
the version of show( ) in A.
Applying Method Overriding
Let’s look at a more practical example that uses method overriding. The following
program creates a superclass called Figure that stores the dimensions of a two-
dimensional object. It also defines a method called area( ) that computes the area
of an object. The program derives two subclasses from Figure. The first is
Rectangle and the second is Triangle. Each of these subclasses overrides area( )
so that it returns the area of a rectangle and a triangle,
respectively.
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
The output from the program is shown here:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
Through the dual mechanisms of inheritance and run-time polymorphism, it is
possible to define one consistent interface that is used by several different, yet
related, types of objects. In this case, if an object is derived from Figure, then its
area can be obtained by calling area( ). The interface to this operation is the same
no matter what type of figure is being used.

You might also like