Developer - Level 2
Introduction of OOPS
One of the major benefits of DRY programming is that, if a piece of information changes in
your program, usually only one change is required to update the code. One of the
biggest nightmares for developers is maintaining code where data is declared over and over
again, meaning any changes to the program become an infinitely more frustrating game of
Where's Waldo? as they hunt for duplicated data and functionality.
OOP is intimidating to a lot of developers because it introduces new syntax and, at a glance,
appears to be far more complex than simple procedural, or inline, code. However, upon
closer inspection, OOP is actually a very straightforward and ultimately simpler approach to
programming.
Introduction of OOPS 4
Android Developer - Level 2
Developers start talking about objects and classes, and they appear to be
interchangeable terms. This is not the case, however.
Right off the bat, there's confusion in OOP: seasoned developers start talking about objects
and classes, and they appear to be interchangeable terms. This is not the case, however,
though the difference can be tough to wrap your head around at first.
A class, for example, is like a blueprint for a house. It defines the shape of the house on
paper, with relationships between the different parts of the house clearly defined and
planned out, even though the house doesn't exist.
An object, then, is like the actual house built according to that blueprint. The data stored in
the object is like the wood, wires, and concrete that compose the house: without being
assembled according to the blueprint, it's just a pile of stuff. However, when it all comes
together, it becomes an organized, useful house.
Classes form the structure of data and actions and use that information to build
objects.
Introduction of OOPS 5
Android Developer - Level 2
Packages
Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub
packages. Many implementations of Java use a hierarchical file system to manage source
and class files. It is easy to organize class files into packages. All we need to do is put
related class files in the same directory, give the directory a name that relates to the purpose
of the classes, and add a line to the top of each class file that declares the package name,
which is the same as the directory name where they reside.
In java there are already many predefined packages that we use while programming.
For example: java.lang , java.io , java.util etc. However one of the most useful feature
of java is that we can define our own packages
Types of package:
1. User defined package: The package we create is called user-defined package.
2. Built-in package: The already defined package like java.io., java.lang. etc are known as
built-in packages.
Defining a Package:
This statement should be used in the beginning of the program to include that program in
that particular package. package <package name>;
Example:
package tools;
public class Hammer {
public void id ()
{
System.out.println ("Hammer");
}
}
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created. A class in java can contain:
data member
method
constructor
block
class and interface
class <class_name>{
data member;
method;
}
In this example, we have created a Student class that have two data members id and name.
We are creating the object of the Student class by new keyword and printing the objects
value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
It can be used to get property value based on the property key. The Properties class
provides methods to get data from properties file and store data into properties file.
Moreover, it can be used to get properties of system.
Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String
returns value based on the key.
key)
Methods
So far, we have only used methods that already exist in Java. But the real power of
programming is in writing our own methods, which we'll learn how to do in this lesson.
meal-time/MealTime.java
import java.io.Console;
Did you feel like you wrote a lot of the same stuff over and over? This code is violating a
programming principle known as DRY, or Don't Repeat Yourself. You will often hear the
phrase DRY up your code.
Writing methods is one way we can DRY up this code base. Let's try it out:
meal-time/MealTime.java
import java.io.Console;
askWhatYouAteFor("breakfast");
String yourBreakfast = myConsole.readLine();
System.out.println("You had " + yourBreakfast + " for breakfast.");
askWhatYouAteFor("lunch");
String yourLunch = myConsole.readLine();
System.out.println("You had " + yourLunch + " for lunch.");
askWhatYouAteFor("dinner");
String yourDinner = myConsole.readLine();
System.out.println("You had " + yourDinner + " for dinner.");
}
Ok, we created a method! Method creation involves a few steps that are going to look pretty
familiar.
1. Type declaration. The public static void thingy should look pretty familiar - it's
similar to the boilerplate we use to set up a program. Like before, I'm going to ask you
to just ignore it for now, as we'll get into its meaning later.
2. Method name. We named our method askWhatYouAteFor . We used a name that is easy
to remember and also easy for other people to understand what our method should do.
3. Parameters. Parens will hold any parameters that the method accepts. The argument
String meal created a variable named meal that you could use inside of the method.
"lunch" . We, can then use the parameter just like any other variable. We are still
repeating ourselves quite a bit, so let's see if we can DRY up our code a little bit more.
meal-time/MealTime.java
import java.io.Console;
We were able to move everything related to each meal into one method call. Now, we aren't
repeating ourselves. Consequently, our main method is also much easier to read.
Also, note that we moved Console myConsole = System.console(); into our whatYouAteFor
method. This is because our console needs to be created inside the method that is going to
use it.
Inheritance
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.
Types of inheritance
1. Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class
only then we call it a single inheritance. The below flow diagram shows that class B extends
only one class which is A. Here A is a parent class of B and B would be a child class of A.
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2. Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or inherits) more than
one base class. The inheritance we learnt earlier had the concept of one base class or
parent. The problem with multiple inheritance is that the derived class will have to manage
the dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted complexity
when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
3. Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from
a derived class, thereby making this derived class the base class for the new class. As you
can see in below flow diagram C is subclass or child class of B and B is a child class of A.
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
4. Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example
class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.
5. Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes
you heard it right. By using interfaces you can have multiple as well as hybrid inheritance
in Java.
Polymorphism
Polymorphism is the capability of a method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations.
It is a feature that allows one interface to be used for a general class of actions.
An operation may exhibit different behavior in different instances.
The behavior depends on the types of data used in the operation.
It plays an important role in allowing objects having different internal structures to share
the same external interface.
Polymorphism is extensively used in implementing inheritance.
Method Overloading
In Java, it is possible to define two or more methods of same name in a class, provided that
there argument list or parameters are different. This concept is known as Method
Overloading.
1. To call an overloaded method in Java, it is must to use the type and/or number of
arguments to determine which version of the overloaded method to actually call.
2. Overloaded methods may have different return types; the return type alone is
insufficient to distinguish two versions of a method. .
3. When Java encounters a call to an overloaded method, it simply executes the version of
the method whose parameters match the arguments used in the call.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
Example:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one
has 2 int parameters and third one is having double arg. The methods are invoked or called
with the same type and number of parameters used.
Output:
a: 10
a and b: 10,20
double a: 5.5
O