OOP-Ktunotes - In-Solved QP 2
OOP-Ktunotes - In-Solved QP 2
2. (a) What is unary operator overloading? Explain with sample code (7)
(b) What is virtual base class? Explain with sample code (8)
1a.
OTE
of Function Overloading and Operator
Examples
K T U N
Example of POP are : C, VB, FORTRAN,
Pascal.
Overloading.
Example of OOP are : C++, JAVA,
VB.NET, C#.NET.
1b.
1) Object : Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one instance of
an object. Each instance of an object can hold its own relevant data.
An Object is a collection of data members and associated member functions also known as methods.
For example whenever a class name is created according to the class an object should be created
without creating object can’t able to use class.
1.
3) Data abstraction & Encapsulation : The wrapping up of data and its functions into a single unit is
called Encapsulation.
When using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class.
Data Abstraction increases the power of programming language by creating user defined data types.
Data Abstraction also represents the needed information in the program without presenting the
details.
Abstraction refers to the act of representing essential features without including the background
details or explanation between them.
For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more
components. To build the Car class, one does not need to know how the different components work
internally, but only how to interface with them, i.e., send messages to them, receive messages from
S . I N
them, and perhaps make the different objects composing the class interact with each other.
OTE
4) Inheritance :
N
Inheritance is the process of forming a new class from an existing class or base class.
derived class.
K T U
The base class is also known as parent class or super class, the new class that is formed is called
Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall
code size of the program, which is an important concept in object-oriented programming.
It is classifieds into different types, they are
The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -
obj, and ++obj but sometime they can be used as postfix as well like
obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for
prefix as well as postfix usage.
#include <iostream>
S . I N
OTE
class Distance {
private:
int feet;
K T U N // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
Distance(int f, int i) {
feet = f;
inches = i;
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
Distance operator- () {
feet = -feet;
inches = -inches;
};
int main() {
// display D1
D2.displayDistance(); // display D2
return 0;
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
class ClassA
{
public:
int a;
};
T U N OTE
};
int c;
K
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output :
A from ClassB : 10
S . I N
A from ClassC : 100
T U N OTE
B : 20
C : 30 K
D : 40
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
3b. One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which makes it
easier to create and maintain an application. This also provides an opportunity to reuse the
code functionality and fast implementation time.
S . I N
When creating a class, instead of writing completely new data members and member
T U OTE
functions, the programmer can designate that the new class should inherit the members of an
N
existing class. This existing class is called the base class, and the new class is referred to as
the derived class. K
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
Where access-specifier is one of public, protected, or private, and base-class is the name of
a previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows −
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
void setHeight(int h) {
height = h;
protected:
int width;
int height;
S . I N
};
T U N OTE
// Derived class
K
class Rectangle: public Shape {
public:
int getArea() {
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
4a. A pointer to a C++ class is done exactly the same way as a pointer to a structure and to
access members of a pointer to a class you use the member access operator -> operator, just
as you do with pointers to structures. Also as with all pointers, you must initialize the
pointer before using it.
Let us try the following example to understand the concept of pointer to a class −
#include <iostream>
S . I N
class Box {
T U N OTE
public:
K
// Constructor definition
length = l;
breadth = b;
height = h;
double Volume() {
private:
};
int main(void) {
ptrBox = &Box1;
S . I N
N OTE
// Save the address of first object
T U
ptrBox = &Box2;
K
// Now try to access a member using member access operator
return 0;
When the above code is compiled and executed, it produces the following
result −
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
// overloaded functions
void test(int);
void test(float);
void test(int, float);
int main()
{
int a = 5;
float b = 5.5;
// Overloaded functions
// with different type and
// number of parameters
S . I N
OTE
test(a);
test(b);
test(a, b);
return 0; K T U N
}
// Method 1
void test(int var)
{
cout << "Integer number: " << var << endl;
}
// Method 2
void test(float var)
{
cout << "Float number: "<< var << endl;
}
// Method 3
void test(int var1, float var2)
{
cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
Run on IDE
Output:
Integer number: 5
S . I N
T U N OTE
K
#include<iostream>
class base
S . I N
public:
T U N OTE
K
virtual void print ()
void show ()
};
public:
void print ()
};
int main()
base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
S . I N
}
T U N OTE
Output:
K
print derived class
6A
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
An android component is simply a piece of code that has a well defined life cycle e.g.
Activity, Receiver, Service etc.
Activity
S . I N
T U N OTE
An activity is a class that represents a single screen. It is like a Frame in AWT.
View
K
A view is the UI element such as button, label, text field etc. Anything that you see is a
view.
Intent
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
For example, you may write the following code to view the webpage.
Service
There are two types of services local and remote. Local service is accessed from within the
application whereas remote service is accessed remotely from other applications running on the same
device.
Content Provider
Fragment
S . I N
OTE
Fragments are like parts of activity. An activity can display one or more fragments on the screen at the
same time.
K T U N
AndroidManifest.xml
It contains informations about activities, content providers, permissions etc. It is like the web.xml file
in Java EE.
It is used to test the android application without the need for mobile or tablet etc. It can be created in
different configurations to emulate different types of real devices.
7b. Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. For example, applications can
also initiate broadcasts to let other applications know that some data has been downloaded to the
device and is available for them to use, so this is broadcast receiver who will intercept this
communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
There is one additional steps in case you are going to implement your custom intents then you will
have to create and broadcast those intents.
@Override
S . I N
OTE
An application listens for specific broadcast intents by registering a broadcast receiver
K T N
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated
U
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has
completed the boot process.
BROADCAST-RECEIVER
<application
android:icon="@drawable/ic_launcher"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
An Intent is a messaging object you can use to request an action from another app component.
Although intents facilitate communication between components in several ways, there are three
fundamental use cases:
S . I N
OTE
Starting an activity
T U N
An Activity represents a single screen in an app. You can start a new instance of an Activity by
K
passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary
data.
If you want to receive a result from the activity when it finishes, call startActivityForResult(). Your
activity receives the result as a separate Intent object in your activity's onActivityResult() callback.
For more information, see the Activities guide.
Starting a service
A Service is a component that performs operations in the background without a user interface. With
Android 5.0 (API level 21) and later, you can start a service with JobScheduler. For more information
about JobScheduler, see its API-reference documentation.
For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of the
Service class. You can start a service to perform a one-time operation (such as downloading a file) by
passing an Intent to startService(). The Intent describes the service to start and carries any necessary
data. If the service is designed with a client-server interface, you can bind to the service from another
component by passing an Intent to bindService(). For more information, see the Services guide.
Delivering a broadcast
Intent types
There are two types of intents: Explicit intents specify which application will satisfy the intent, by
supplying either the target app's package name or a fully-qualified component class name. You'll
typically use an explicit intent to start a component in your own app, because you know the class
name of the activity or service you want to start. For example, you might start a new activity within
your app in response to a user action, or start a service to download a file in the background.
Implicit intents do not name a specific component, but instead declare a general action to perform,
which allows a component from another app to handle it. For example, if you want to show the user a
location on a map, you can use an implicit intent to request that another capable app show a specified
location on a map.
An intent filter is an expression in an app's manifest file that specifies the type of intents that the
component would like to receive. For instance, by declaring an intent filter for an activity, you make it
possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do
not declare any intent filters for an activity, then it can be started only with an explicit intent.
Building an intent
I N
An Intent object carries information that the Android system uses to determine which component to
S .
OTE
start (such as the exact component name or component category that should receive the intent), plus
information that the recipient component uses in order to properly perform the action (such as the
T U N
action to take and the data to act upon).
K
The primary information contained in an Intent is the following:
Component name
This is optional, but it's the critical piece of information that makes an intent explicit, meaning that the
intent should be delivered only to the app component defined by the component name. Without a
component name, the intent is implicit and the system decides which component should receive the
intent based on the other intent information (such as the action, data, and category—described below).
If you need to start a specific component in your app, you should specify the component name.
Note: When starting a Service, always specify the component name. Otherwise, you cannot be certain
what service will respond to the intent, and the user cannot see which service starts.
Action
A string that specifies the generic action to perform (such as view or pick).
In the case of a broadcast intent, this is the action that took place and is being reported. The action
largely determines how the rest of the intent is structured—particularly the information that is
contained in the data and extras.
You can specify your own actions for use by intents within your app (or for use by other apps to
invoke components in your app), but you usually specify action constants defined by the Intent class
or other framework classes. Here are some common actions for starting an activity:
ACTION_VIEW
Use this action in an intent with startActivity() when you have some information that an activity can
show to the user, such as a photo to view in a gallery app, or an address to view in a map app.
ACTION_SEND
Also known as the share intent, you should use this in an intent with startActivity() when you have
some data that the user can share through another app, such as an email app or social sharing app.
Data
The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data. The
type of data supplied is generally dictated by the intent's action. For example, if the action is
ACTION_EDIT, the data should contain the URI of the document to edit.
When creating an intent, it's often important to specify the type of data (its MIME type) in addition to
its URI. For example, an activity that's able to display images probably won't be able to play an audio
file, even though the URI formats could be similar. Specifying the MIME type of your data helps the
Android system find the best component to receive your intent. However, the MIME type can
sometimes be inferred from the URI—particularly when the data is a content: URI. A content: URI
indicates the data is located on the device and controlled by a ContentProvider, which makes the data
MIME type visible to the system.
To set only the data URI, call setData(). To set only the MIME type, call setType(). If necessary, you
can set both explicitly with setDataAndType().
Caution: If you want to set both the URI and MIME type, don't call setData() and setType() because
they each nullify the value of the other. Always use setDataAndType() to set both URI and MIME
type.
Category- A string containing additional information about the kind of component that should handle
the intent. Any number of category descriptions can be placed in an intent, but most intents do not
require a category. Here are some common categories:
CATEGORY_BROWSABLE
The target activity allows itself to be started by a web browser to display data referenced by a link,
such as an image or an e-mail message.
CATEGORY_LAUNCHER
The activity is the initial activity of a task and is listed in the system's application launcher.
See the Intent class description for the full list of categories.
These properties listed above (component name, action, data, and category) represent the defining
characteristics of an intent. By reading these properties, the Android system is able to resolve which
app component it should start. However, an intent can carry additional information that does not affect
how it is resolved to an app component. An intent can also supply the following information:
Extras - Key-value pairs that carry additional information required to accomplish the requested action.
Just as some actions use particular kinds of data URIs, some actions also use particular extras.
You can add extra data with various putExtra() methods, each accepting two parameters: the key
name and the value. You can also create a Bundle object with all the extra data, then insert the Bundle
in the Intent with putExtras().
Every application must have an AndroidManifest.xml file (with precisely that name) in its root
directory. The manifest file provides essential information about your app to
theAndroid system, which the system must have before it can run any of the app's code. ...
It names the Java package for the application.
If you want to change the name of your app, then the manifest file isn't the place to look
for. Your app name can be changed from strings.xml file in the res/values/ folder. You can
do any formatting from within Eclipse itself during the development of your project/app
The Android System searches all apps for an intent filter that matches the intent. ...
An intent filter is an expression in an app's manifest file that specifies the type
ofintents that the component would like to receive.
An activity represents a single screen with a user interface just like window or frame of
Java.Android activity is the subclass of ContextThemeWrapper class.
A drawable resource is a general concept for a graphic that can be drawn to the screen and
which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource
with attributes such as android:drawable and android:icon. There are several different types
of drawables: Bitmap File
A bitmap graphic file (.png, .jpg, or .gif). Creates a BitmapDrawable.
Nine-Patch File
A PNG file with stretchable regions to allow image resizing based on content (.9.png).
Creates a NinePatchDrawable.
Layer List
A Drawable that manages an array of other Drawables. These are drawn in array order, so
the element with the largest index is be drawn on top. Creates a LayerDrawable.
State List
An XML file that references different bitmap graphics for different states (for example, to use
a different image when a button is pressed). Creates a StateListDrawable.
Level List
An XML file that defines a drawable that manages a number of alternate Drawables, each
assigned a maximum numerical value. Creates a LevelListDrawable.
Transition Drawable
An XML file that defines a drawable that can cross-fade between two drawable resources.
Creates a TransitionDrawable.
Inset Drawable
An XML file that defines a drawable that insets another drawable by a specified distance.
This is useful when a View needs a background drawble that is smaller than the View's
actual bounds.
Clip Drawable
An XML file that defines a drawable that clips another Drawable based on this Drawable's
current level value. Creates a ClipDrawable.
Scale Drawable
An XML file that defines a drawable that changes the size of another Drawable based on its
current level value. Creates a ScaleDrawable
Shape Drawable
An XML file that defines a geometric shape, including colors and gradients. Creates a
ShapeDrawable.
9b. A style resource defines the format and look for a UI. A style can be applied to an individual View
(from within a layout file) or to an entire Activity or application (from within the manifest file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the
layout. This XML file resides under res/values/ directory of your project and will
have <resources> as the root node which is mandatory for the style file. The name of the
XML file is arbitrary, but it must use the .xml extension.
You can define multiple styles per file using <style> tag but each style will have its name
that uniquely identifies the style. Android style attributes are set using <item> tag as shown
below −
<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or
other value depending on the style property.