OOP Chapter - 2
OOP Chapter - 2
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;
}
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:
}
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:
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 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);
}
}
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.
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:
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();
}
}
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
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