Anda di halaman 1dari 14

Android

Developer - Level 2

Introduction of OOPS

Understanding Object-Oriented Programming


Object-oriented programming is a style of coding that allows developers to group similar
tasks into classes. This helps keep code following the tenet "don't repeat yourself" (DRY)
and easy-to-maintain.

"Object-oriented programming is a style of coding that allows developers to group


similar tasks into classes."

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.

Understanding Objects and Classes


Before you can get too deep into the finer points of OOP, a basic understanding of the
differences between objects and classes is necessary. This section will go over the building
blocks of classes, their different capabilities, and some of their uses.

Recognizing the Differences Between Objects and Classes

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, Class, Properties & Methods

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

Advantages of using a package


Before discussing how to use them Let see why we should use packages.

Reusability: Reusability of code is one of the most important requirements in the


software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.
Easy to locate the files.
In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to name-space collisions. Packages are a way of avoiding
name-space collisions.

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>;

Packages, Class, Properties & Methods 6


Android Developer - Level 2

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

Syntax to declare a class:

class <class_name>{
data member;
method;
}

Simple Example of Object and Class

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)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Packages, Class, Properties & Methods 7


Android Developer - Level 2

Properties class in Java


The properties object contains key and value pair both as a string. It is the subclass of
Hashtable.

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.

Advantage of properties file


Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.

Methods of Properties class


The commonly used methods of Properties class are given below.

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)

public void setProperty(String


sets the property in the properties object.
key,String value)
public void store(Writer w, String
writers the properties in the writer object.
comment)
public void store(OutputStream os,
writes the properties in the OutputStream object.
String comment)

storeToXML(OutputStream os, writers the properties in the writer object for


String comment) generating xml document.
writers the properties in the writer object for
public void storeToXML(Writer w,
generating xml document with specified
String comment, String encoding)
encoding.

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.

Packages, Class, Properties & Methods 8


Android Developer - Level 2

Write this code out first:

meal-time/MealTime.java

import java.io.Console;

public class MealTime {


public static void main(String[] args) {
Console myConsole = System.console();

System.out.println("What did you eat for breakfast?");


String yourBreakfast = myConsole.readLine();
System.out.println("You had " + yourBreakfast + " for breakfast.");

System.out.println("What did you eat for lunch?");


String yourLunch = myConsole.readLine();
System.out.println("You had " + yourLunch + " for lunch.");

System.out.println("What did you eat for dinner?");


String yourDinner = myConsole.readLine();
System.out.println("You had " + yourDinner + " for dinner.");
}
}

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

Packages, Class, Properties & Methods 9


Android Developer - Level 2

import java.io.Console;

public class MealTime {


Console myConsole = System.console();

public static void main(String[] args) {

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.");
}

public static void askWhatYouAteFor(String meal) {


System.out.println("What did you eat for " + meal + "?");
}
}

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.

When the method is called, like whatYouAteFor("breakfast") , the parameter, meal ,


takes on the value of the argument, "breakfast" . Similarly, when we call
whatYouAteFor("lunch") , the parameter, meal , takes of the value of the argument,

"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

Packages, Class, Properties & Methods 10


Android Developer - Level 2

import java.io.Console;

public class MealTime {


public static void main(String[] args) {
askWhatYouAteFor("breakfast");
askWhatYouAteFor("lunch");
askWhatYouAteFor("dinner");
}

public static void askWhatYouAteFor(String meal) {


Console myConsole = System.console();
System.out.println("What did you eat for " + meal + "?");
String yourMeal = myConsole.readLine();
System.out.println("You had " + yourMeal + " for " + meal + ".");
}
}

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.

Packages, Class, Properties & Methods 11


Android Developer - Level 2

Inheritance, Polymorphism & Overloading

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.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

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
}

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.

Inheritance, Polymorphism & Overloading 12


Android Developer - Level 2

Single Inheritance example program in Java

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.

Inheritance, Polymorphism & Overloading 13


Android Developer - Level 2

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.

Multilevel Inheritance example program in Java

Inheritance, Polymorphism & Overloading 14


Android Developer - Level 2

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

Inheritance, Polymorphism & Overloading 15


Android Developer - Level 2

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.

Inheritance, Polymorphism & Overloading 16


Android Developer - Level 2

6. It can have different access modifiers.

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

Inheritance, Polymorphism & Overloading 17

Anda mungkin juga menyukai