Sei sulla pagina 1di 16

ASSIGNMENT NO 2

BILAL AHMED
BT428808
PL-2 (3411)
AUTUMN 2019
BSCS

Q 1: What is the role of class in a object-oriented programming language? What


is the difference a structure in structured programming language and a class in
object-oriented programming language? Elaborate your answer with
programming example?
Ans: In object-oriented programming, a class is an extensible program-code-template for
creating objects, providing initial values for state (member variables) and implementations of
behavior (member functions or methods). ... In these languages, a class that
creates classes is called a multiclass.

Structured Programming

1. Structured Programming is designed which focuses on process.


2. Structured programming follows top-down approach.
3. In Structured Programming, Programs are divided into small self
contained functions
4. Structured Programming provides less reusability, more function dependency.
5. Less abstraction and less flexibility.
Object Oriented Programming

1. Object Oriented Programming is designed which focuses on data.


2. Object oriented programming follows bottom-up approach.
3. In Object Oriented Programming, Programs are divided into small entities
called objects
4. Object Oriented Programming provides more reusability, less
function dependency.
5. More abstraction and more flexibility.

class Car(object):
def __init__(self, model, passengers, color, speed):
self.model = model
self.passengers = passengers
self.color = color
self.speed = speed

def accelerate(self):
self.speed = self.speed + 2
print (self.speed)

bmw = Car("BMW", 4, "red", 5)


ferrari = Car("Ferrari", 2, "black", 10)
ford = Car("Ford", 6, "blue", 6)

bmw.accelerate()
print (bmw.color)

ferrari.accelerate()
print (ferrari.color)
ferrari.accelerate() ]

print (ford.passengers)
ford.accelerate()
“Difference Between structure in structure programming language and
Class in object oriented programming language”
Structured Programming:
1. Structured Programming is designed which focuses on process.
2. Structured programming follows top-down approach.
3. In Structured Programming, Programs are divided into small self-
contained functions.
4. Structured Programming provides less reusability, more function
dependency.
5. Less abstraction and less flexibility.

Object Oriented Programming:


1. Object Oriented Programming is designed which focuses on data.
2. Object oriented programming follows bottom-up approach.
3. In Object Oriented Programming, Programs are divided into small
entities called objects
4. Object Oriented Programming provides more reusability, less
function dependency.
5. More abstraction and more flexibility.

Question#2
Why inheritance is needed in object-oriented programming
languages? Write a program in java to demonstrate the concept
of inheritance and polymorphism.
“The Importance of Inheritance Within OOP”:
In an object-oriented programming language that is well designed,
a function should be able to have functions that reside inside it. In addition to
this, other functions should be processed as input and output as well. When an
OOP language uses these features, it will utilize a design that is simple and
consistent.
This is an important concept that can make the difference between a
good programming language and a great programming language. When code is
written, the subroutine should be capable of returning a function. When this is
done, the argumentcan be raised to a higher nth power. Once this has occurred, it
can be used in a number of different ways.
For example, when two arguments are taken, one can be used as a
function. It can be applied to different arguments many times over, and the result
will stay the same. It will be computed by utilizing a mathematical notion. It can
also be used to implement a number of different systems, and it can help you find
solutions to problems that deal with iteration. It may also be possible for
elements or variables to have a third range of the true or false function. It could
be used as an additional method to decide when the nesting process should be
terminated. When it is viewed in this format, it is the same as being in the "while
loop" that is often viewed in procedural programming languages.
It is also important for you to understand compositions. The
function composition is a mathematical concept. If you use two functions within a
sequence, you can look at it as being a single function that is a composition of the
elements or variables. In mathematics, it may be seen as being viewed in a
number of different ways. In a nutshell, the function will take a set number of
arguments, and it will return one function of the composition. A subroutine will
need to be defined. For example, even if the function is a power of two, the name
and the function will be two different elements. In OOP languages that are well
designed, the definition of a function and a name of a function will not be
inseparable.
Because OOP languages use such a strong linguistic system, classes
can be written by simply extending older subroutines. This can be done in a way
that will allow the new subroutine to hold all the variables and classes of a simple
subroutine with having to deal with the old code that may appear in the body of
the class. This is the foundation of inheritance. Inheritance will occur when an
object inherits data or traits from its parent. Each superclass will be composed of
subclasses, and plays an important role in the object-oriented programming
paradigm.

Program:
Main Class:-
package file
public class File {
public static void main (String [] args) {
Cal obj = new Cal ();
int z=7;
obj.sum();
Cal obj1 = new Cal();
obj1.sum();
}
}
Sub Class:-
public class Cal {

public void sum(){


int a=7;
int b=8;
System.out.println(a+b);

}
public void sum(int a){
int b=7;
System.out.println(a+b);

}
}
Extend Class:-
package file;

public class calculate extends Cal {

Question no 03:
What are exceptions? How exceptions are handled in Java? Write
a program in java to demonstrate the handling of exception and
use try/catch block.
Definition: An exception is an event, which occurs during the execution
of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object


and hands it off to the runtime system. The object, called an exception object,
contains information about the error, including its type and the state of the
program when the error occurred. Creating an exception object and handing it to
the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to


find something to handle it. The set of possible "somethings" to handle the
exception is the ordered list of methods that had been called to get to the
method where the error occurred. The list of methods is known as the call
stack (see the next figure).

The call stack.

The runtime system searches the call stack for a method that contains
a block of code that can handle the exception. This block of code is called
an exception handler. The search begins with the method in which the error
occurred and proceeds through the call stack in the reverse order in which the
methods were called. When an appropriate handler is found, the runtime system
passes the exception to the handler. An exception handler is considered
appropriate if the type of the exception object thrown matches the type that can
be handled by the handler.

The exception handler chosen is said to catch the exception. If the


runtime system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, as shown in the next figure, the runtime
system (and, consequently, the program) terminates.
Searching the call stack for the exception handler.

Program: -
class Example1 {

public static void main(String args[]) {

int num1, num2;

try {

/* We suspect that this block of statement can throw

* exception so we handled it by placing these statements

* inside try and handled the exception in catch block

*/

num1 = 0;

num2 = 62 / num1;

System.out.println(num2);

System.out.println("Hey I'm at the end of try block");

catch (ArithmeticException e) {

/* This block will only execute if any Arithmetic exception

* occurs in try block

*/

System.out.println("You should not divide a number by zero");


}

catch (Exception e) {

/* This is a generic Exception handler which means it can handle

* all the exceptions. This will execute if the exception is not

* handled by previous catch blocks.

*/

System.out.println("Exception occurred");

System.out.println("I'm out of try-catch block in Java.");

Output:

You should not divide a number by zero

I'm out of try-catch block in Java.

Question no 04:
Why packages are used in Java programming language? Write a
program in java to describe the procedure of creating a package
in Java.
Packages are used in Java in order to prevent naming conflicts, to
control access, to make searching/locating and usage of classes, interfaces,
enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes,


interfaces, enumerations and annotations) providing access protection and
namespace management.

Some of the existing packages in Java are −

 java. lang − bundles the fundamental classes


 java.io − classes for input, output functions are bundled in this package

Programmers can define their own packages to bundle group of


classes/interfaces, etc. It is a good practice to group related classes implemented
by you so that a programmer can easily determine that the classes, interfaces,
enumerations, and annotations are related.

Since the package creates a new namespace there won't be any name
conflicts with names in other packages. Using packages, it is easier to provide
access control and it is also easier to locate the related classes.

“Creating a Package”

While creating a package, you should choose a name for the package
and include a package statement along with that name at the top of every source
file that contains the classes, interfaces, enumerations, and annotation types that
you want to include in the package.

The package statement should be the first line in the source file. There
can be only one package statement in each source file, and it applies to all types
in the file.

If a package statement is not used then the class, interfaces,


enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements, you have to use
-d option as shown below.
Java c -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified
destination, and the compiled class files will be placed in that folder.

Example:

Let us look at an example that creates a package called animals. It is a good


practice to use names of packages with lower case letters to avoid any conflicts
with the names of classes and interfaces.

Following package example contains interface named animals −

/* File name: Animal.java */

Package animals;

Interface Animal {

Public void eat ();

Public void travel ();

Question no 05:
What is the difference between CLI and GUI? Briefly discuss few
of the GUI packages used in java with a suitable programming
example.

 “What is GUI”
GUI stands for Graphical User Interface. It takes the advantage of
computer graphics. It allows the user to interact with the computer using
components such as windows, icons, labels, text boxes, and radio buttons. It is
easy for the user to perform tasks using GUI as it does not require remembering
commands. He can easily click on icons, drag and drop objects using the mouse.

Operating Systems such as Windows and Linux provide GUI. They


contain windows, icons, search boxes, menus, drop down lists and many graphical
elements. There is also application software designed for specific business
requirements such as Human Resource Management systems, Library
Management Systems, etc. They consist of GUIs to accomplish necessary tasks.
Overall, a GUI is a user-friendly mechanism to interact with the system.
 “What is CLI”
CLI stands for Command Line Interface. CLI is also called Command
Language Interpreter, Console User Interface or Character User Interface. It
allows the users to enter commands to the terminal to perform the task. When
the user enters a command and presses “enter” key, the terminal or the shell will
interpret that command and will display the response back to the terminal.
Likewise, the user can communicate with the operating system.
Figure 2: Linux Command Line interface
The user should have a good understanding to use the CLI. He
should thoroughly know the correct syntax to issue effective commands.
Operating systems such as UNIX contains a CLI while OS such as Windows and
Linux contain both CLI and GUI. Overall, CLI is memory efficient and faster in
execution than the GUI.

“Difference Between GUI and CLI”


Definition:
A GUI is a type of user interface that allows users to interact with
electronic devices through graphical icons and visual indicators. A CLI is an
interface for the user to issue commands in the form of successive lines of text or
command lines to perform the tasks.
 Stands for: GUI stands for Graphical User Interface whereas CLI stands for
Command Line Interface.
 Usability: It is easy to use the GUI. It is not necessary to have a vast
knowledge to operate the system using the GUI. Even a beginner can easily
handle the tasks using the GUI. On the other hand, CLI is complex. The user
should have goodknowledge of the commands. Misspelt commands are of
no use.
 Memory Requirement: GUI requires more memory as it contains a lot of
graphical components. CLI is a command interface, and it does not require
more memory.
 Speed: GUI is slower but the CLI is fast.
 Customizability: The user can change the appearance of the GUI. There
are customizable options to change the appearance. It is not possible to
change the CLI.
 Flexibility: GUI is more flexible whereas CLI is not much flexible.
 Conclusion: The difference between GUI and CLI is that the GUI allows the
user to interact with the system using graphical elements such as windows,
icons, menus while the CLI allows the user to interact with the system using
commands. In brief, GUI is more user-friendly, and CLI is more advanced
and powerful.

Programming examples: -
import java.awt.Frame; // Using Frame class in package java.awt

// A GUI program is written as a subclass of Frame - the top-level container

// This subclass inherits all properties from Frame, e.g., title, icon, buttons,
content-pane

public class MyGUIProgram extends Frame {


// private variables

......

// Constructor to setup the GUI components

public MyGUIProgram() { ...... }

// methods

// The entry main() method

public static void main(String[] args) {

// Invoke the constructor (to setup the GUI) by allocating an instance

new MyGUIProgram();

Example#2

Button btnColor = new Button("Red"); // Declare and allocate a Button instance


called btnColor

add(btnColor); // "this" Container adds the Button

...

btnColor.setLabel("Green"); // Change the button's label

btnColor.getLabel(); // Read the button's label


...

Potrebbero piacerti anche