What is OOP?
Object-oriented programming (OOP) refers to a type of computer programming (software design) in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.
Main Characteristics And
Features Of Object Oriented Programming
According to the
principals there twelve fundamental features there are given below.
1.
Encapsulation
2.
Data Abstraction
3.
Inheritance
4.
Polymorphism
5.
Extensibility
6.
Persistence
7.
Delegation
8.
Generality
9.
Object Concurrency
10.
Event Handling
11.
Multiple Inheritance
12.
Message Passing
How to achieve Abstraction ?
There are
two ways to achieve abstraction in java
Ø Abstract class (0 to 100%)
Ø Interface (Achieve 100% abstraction)
State or Life cycle of thread
State
of a thread are classified into five types they are
1.
New State
2.
Ready State
3.
Running State
4.
Waiting State
5. Halted or dead State
Achieve multithreading in java
In
java language multithreading can be achieve in two different ways.
1.
Using thread class
2.
Using Runnable interface
Using thread class
In
java language multithreading program can be created by following below rules.
1.
Create any user defined
class and make that one as a derived class of thread class.
Class Class_Name extendsThread
{
........
}
2.
Override run() method of
Thread class (It contains the logic of perform any operation)
3.
Create an object for
user-defined thread class and attached that object to predefined thread class
object.
Class_Name
obj=new Class_Name Thread t=new Thread(obj);
4.
Call start() method of
thread class to execute run() method.
5.
Save the program with
filename.java
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
Example of multithreading using Thread class
Thread
based program for displaying 1 to 10 numbers after each and every second.
// Threaddemo2.java
Class Th1 extendsThread
{
Public
void run()
{
try
{
for(int i=1;i< =10;i++)
{
System.out.println("value
of i="+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.err.println("Problem in thread
execution");
}
}
}
classThreaddemo2
{
Public
static void main(String args[])
{
Th1 t1=new Th1();
System.out.println("Execution
status of t1 before start="+t1.isAlive());
t1.start();
System.out.println("Execution status of t1 before
start="+t1.isAlive());
try
{
Thread.sleep(5000);
}
catch(InterruptedException ie)
{
System.out.println("Problem
in thread execution");
}
System.out.println("Execution
status of t1 during execution="+t1.isAlive());
try
{
Thread.sleep(5001);
}
catch(InterruptedException ie)
{
System.out.println("problem
in thread execution");
}
System.out.println("Execution
status of t1 after completation="+t1.isAlive());
}
}
Output
Execution status of t1 before start=false//new state
Execution status of t1 after start=true//ready state
1
2
3
4
5
6
Execution status of t1 during execution=true //running
state
7
8
9
10
Execution status of t1 after completation=false //halted
state
ANOTHER
EXAPLE:
class MultithreadingDemo extendsThread
{
public
voidrun()
{
try
{
//
Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +" is running");
}
catch (Exception e)
{
//
Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread // Main Class
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo
object = new MultithreadingDemo();
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
Constructors of Thread
class
Ø Thread()
Ø Thread(String name)
Ø Thread(object)
Ø Thread(object, String name)
Methods of Thread class
Ø getPriority()
Ø setPriority()
Ø getName()
Ø setName()
Ø isDeamon()
Ø run()
Ø start()
Ø sleep()
Ø suspend()
Ø resume()
Ø stop()
Ø isAlive()
Ø currentThread()
Ø join()
Ø getState()
Ø yield()
Using Runnable Interface
Runnable
is one of the predefined interface in java.lang package, which is containing
only one method and whose prototype is " Public abstract void run "
The
run() method of thread class defined with null body and run() method of
Runnable interface belongs to abstract. Industry is highly recommended to
override abstract run() method of Runnable interface but not recommended to
override null body run() method of thread class.
In
some of the circumstance if one derived class is extending some type of
predefined class along with thread class which is not possible because java
programming never supports multiple inheritance. To avoid this multiple
inheritance problem, rather than extending thread class we implement Runnable
interface.
Rules to create the thread using Runnable
interface
Ø Create any user defined class and implements
runnable interface within that
Ø Override run() method within the user defined
class.
Ø call start() method to execute run() method of
thread class
Save
the program with classname.java
2) Java Thread Example by implementing Runnable
interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
Example of thread using Runnable interface
public class CreateThreadRunnableExample implements Runnable{
publicvoid run(){
for(int i =0; i <5; i++){
System.out.println("Child Thread : "+ i);
try{
Thread.sleep(50);
}
catch(InterruptedException ie){
System.out.println("Child thread interrupted! "+ ie);
}
}
System.out.println("Child thread finished!");
}
publicstaticvoid main(String[] args){
Thread t =newThread(newCreateThreadRunnableExample(),"My Thread");
t.start();
for(int i =0; i <5; i++){
System.out.println("Main thread : "+ i);
try{
Thread.sleep(100);
}
catch(InterruptedException ie){
System.out.println("Child thread interrupted! "+ ie);
}
}
System.out.println("Main thread finished!");
}
}
ANOTHER EXAMPLE
class MultithreadingDemo implements Runnable
{
public voidrun()
{
try
{
// Displaying the thread
that is running
System.out.println ("Thread " + Thread.currentThread().getId() "
is running");
}
catch (Exception e)
{
//
Throwing an exception
System.out.println ("Exception is caught");
}
}
}
class Multithread
// Main Class
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread
object = newThread(new MultithreadingDemo());
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still extend
other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some
inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
What if we call run()
method directly instead start() method?
Ø Each
thread starts in a separate call stack.
Ø Invoking
the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}
Output:running...
Problem
if you direct call run() method
class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the
above program that there is no context-switching because here t1 and t2 will be
treated as normal object not thread object.
Difference between "implements
Runnable" and "extends Thread" in Java
1. Inheritance
Option: The
limitation with "extends Thread" approach is that if you extend
Thread, you can not extend anything else . Java does not support multiple
inheritance. In reality , you do not need Thread class behavior , because
in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you
the choice to extend any class you like , but still define behavior that will
be run by separate thread.
2. Reusability
: In
"implements Runnable" , we are creating a different Runnable
class for a specific behavior job (if the work you want to be done
is job). It gives us the
freedom to reuse the specific
behavior job whenever required.
"extends Thread" contains both
thread and job specific behavior code. Hence once thread completes execution ,
it can not be restart again.
3. Object Oriented Design: Implementing Runnable should
be preferred . It does not specializing or modifying the thread behavior . You
are giving thread something to run. We conclude that Composition is the better
way. Composition means two objects A and B satisfies has-a relationship.
"extends Thread" is not a good
Object Oriented practice.
4.
Loosely-coupled : "implements
Runnable" makes the code loosely-coupled and easier to read .Because the
code is split into two classes . Thread class for the thread specific code and
your Runnable implementation class for your job that should be run by a
thread code.
"extends Thread" makes the code
tightly coupled . Single class contains the thread code as well as the job that
needs to be done by the thread.
5. Functions
overhead : "extends
Thread" means inheriting all the functions of the Thread class which
we may do not need . job can
be done easily by Runnable without the Thread class functions overhead.
Example of "implements Runnable" and
"extends Thread"
public class RunnableExample implements
Runnable {
public void run()
{
System.out.println("Alive
is awesome");
}
}
public class ThreadExample extends Thread
{
public void run()
{
System.out.println("
Love Yourself ");
}
}
a) Extends
Thread Class
class
MyThread extends Thread
{
@Override
public void run()
{//Keep the task to be performed here
}
}
public class MainClass
{
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.start();
}
}
b) Implements
Runnable Interface
class
MyRunnable implements Runnable
{
@Override
public void run()
{//Keep the task to be performed here
}
}
public class MainClass
{
public static void main(String[] args)
{
MyRunnable runnable = new MyRunnable();
Thread t = new
Thread(runnable);
t.start();
}
}
Extends
Thread Vs Implements Runnable In Java :
Implements
Runnable |
Extends
Thread |
You can extend any other class. |
You can’t extend any other class. |
No overhead of additional methods . |
Overhead of additional methods from Thread class. |
Separates the task from the runner. |
Doesn’t separate the task from the runner. |
Best object oriented programming practice. |
Not a good object oriented programming practice. |
Loosely coupled. |
Tightly coupled. |
Improves the reusability of the code. |
Doesn’t improve the reusability of the code. |
More generalized task. |
Thread specific task. |
Maintenance of the code will be easy. |
Maintenance of the code will be time consuming. |
The most common difference is
When you extends Thread
class, after that you can’t extend any other class
which you required. (As you know, Java does not allow inheriting more than one
class).
When you implements Runnable
, you can save a space for your class to extend any other
class in future or now.
·
Java doesn't support
multiple inheritance, which means you can only extend one class in Java so once
you extended Thread class you lost your chance and can not extend or inherit
another class in Java.
·
In Object oriented
programming extending a class generally means adding new functionality,
modifying or improving behaviors. If we are not making any modification on
Thread then use Runnable interface instead.
·
Runnable interface
represent a Task which can be executed by either plain Thread or Executors or
any other means. so logical separation of Task as Runnable than Thread is good
design decision.
·
Separating task as
Runnable means we can reuse the task and also has liberty to execute it from
different means. since you can not restart a Thread once it completes. again
Runnable vs Thread for task, Runnable is winner.
·
Java designer
recognizes this and that's why Executors accept Runnable as Task and they have
worker thread which executes those task.
Inheriting all Thread methods are additional overhead just for
representing a Task which can be done easily with Runnable.
Write a Program to determine perfect number in
Java. [BWDB-2018]
Perfect Number
A number is a perfect number
if is equal to sum of its proper divisors, that is, sum of its positive
divisors excluding the number itself. Write a function to check if a given
number is perfect or not.
Examples:
Input: n =
15
Output:
false
Divisors of
15 are 1, 3 and 5. Sum of
divisors is
9 which is not equal to 15.
Input: n =
6
Output:
true
Divisors of
6 are 1, 2 and 3. Sum of
divisors is
6.
#include<iostream>
using
namespace std;
bool isPerfect(long long int
n)
{
long
long int sum = 1;
for (long long int i=2; i*i<=n; i++)
if (n%i==0)
sum = sum + i + n/i;
if (sum == n && n != 1)
return true;
return
false;
}
int main()
{
int n;
cin>>n;
if (isPerfect(n))
cout << n << " is
a perfect numbern";
else
cout<<n<<"is not a
perfect number";
return 0;
}
Another solution –
#include
<stdio.h>
int
main()
{
int i, num, sum =
0;
printf("Enter any number to check
perfect number: ");
scanf("%d", &num);
for(i=1; i<num;
i++)
{
if(num%i == 0)
{
sum += i;
}
}
if(sum == num)
{
printf("%d is PERFECT
NUMBER", num);
}
else
{
printf("%d is NOT PERFECT
NUMBER", num);
}
return
0;
}
Perfect number
calculation in java
package
FrequentPrograms;
import
java.util.Scanner;
public
class PerfectNumberUsingFor
{
private
static Scanner sc;
public
static void main(String[] args) {
int i, Number, Sum = 0 ;
sc = new Scanner(System.in);
System.out.println("\n
Please Enter any Number: ");
Number = sc.nextInt();
for(i = 1 ; i < Number
; i++) {
if(Number % i == 0) {
Sum = Sum + i;
}
}
if (Sum == Number) {
System.out.format("\n% d is a Perfect Number", Number);}
else {
System.out.format("\n% d
is NOT a Perfect Number", Number);
}
}
}
What is the output of the Program?[Bangladesh Water Development Board, AP, -2018]
#include<stdio.h>
using
namespace std;
intmain()
{
int i=-1,J=-1,k=O,l=2,m;
m=i++
&& j++ && k++||l++;
printf("%d
%d %d %d %d",i,J,k,l,m);
return 0;
}
output:
-0, 0, 1, 3, 1
Output
of following Java program?
[BWDB-2018]
class Base {
public
void Print() {
System.out.println("Base");
}
}
class Derived extends Base {
public
void Print() {
System.out.println("Derived");
}
}
class Main{
public static void DoPrint( Base o ) {
o.Print();
}
public static void main(String[] args) {
Base x = new Base();
Base y = new Derived();
Derived z = new Derived();
DoPrint(x);
DoPrint(y);
DoPrint(z);
}
}
Output-
Base
Derived
Derived
String
reverse using recursive function in C [Eastern refinery 2017, ministry aptitute
test-2018,19]
#include <stdio.h>
#include <string.h>
void reverse(char
[], int, int);
int main()
{
char str1[20];
int size;
printf("Enter a string to reverse: ");
scanf("%s", str1);
size = strlen(str1);
reverse(str1, 0, size - 1);
printf("The string after reversing is: %s\n", str1);
return 0;
}
void reverse(char str1[], int index, int size)
{
char temp;
temp = str1[index];
str1[index] = str1[size - index];
str1[size - index] = temp;
if (index
== size / 2)
{
return;
}
reverse(str1, index + 1, size);
}
What will be the output of the following
program[Bangladesh Water Development Board, AP,-2018]
#include<iostream>
using
namespace std;
class A{
private:
int a;
int
b;
void set_a(int a){
this->a=a;
}//set
value of b
void set_b(int b){
this->b=b;
}
public:
void getValues(int x,int y){
set_a(x);//calling
private member function
set_b(y);//calling
private member function
}
void putValues(){ //printing values of private
data members a,b
cout<<"a="<<a<<",b="<<b<<endl;
}
};
int main(){
A
objA; //set values to class data
nembers
objA.getValues(100,200); //print values
objA.putValues();
return 0;
}
Write a C++ code to access protected data -> friend class[Bangladesh Water Development Board, AP, -2018]
Solution-
Well, if you have control
over base, you could add the friend on the base (which semantically is what
you're really trying to do.)
The following code snippet
compiles. A derived class retains the friendship access of its base, without
that having to seep down to its own properties. incr
will
not have access to derived
's private
members.
class base
{
protected:
int b;
friend void incr();
};
class derived : public base
{
};
derived obj;
void incr()
{
obj.b ++;
}
int main()
{
return 0;
}
This works too:
class
base
{
protected:
int
b;
};
class
derived : public base
{
friendvoid incr();
protected:
int c;
};
derived
obj;
void incr()
{
obj.b ++;
obj.c ++;
}
int
main()
{
return
0;
}
Pattern print in Java[BWDB-2018]
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Class
TestJaggedArray{
public static void main(String[] args){
int
arr[][]=new int[5][];
arr[0]=new int[1];
arr[1]=new int[2];
arr[2]=new int[3];
arr[3]=new int[4];
arr[4]=new int[5];
//initializingajagged
array
for(int i=0;i<arr.length;
i++)
{count=1;
for(int
j=0; j<arr[i].length; j++)
arr[i][j]=count++;
}
//ptinting
the data of a jagged array
for(int i=0;i<arr.length;i++){
for(int j=0; j<arr[i].length;j++){
System.out.print (arr[i][j]+" ");
}
System.out.println(); //new
line
}
}
}
Java string to Camel Case and display camel case[Bangladesh Water Development Board, AP, -2018]
Writesimple
java program toconvert string into camel case and display camel case string.
Public class CaseConverter{
String camelCase(String str)
{
StringBuilder builder=new StringBuilder (str);
// Flag to keep track if last visited
characteris a white space or not
boolean isLastSpace=true;
//Iterate String from beginning to end.
for(inti=O;i<builder.length();i++)
{
char ch=builder.charAt(i);
if(isLastSpace && ch>='a' && ch<='z')
{
//Character need to be converted to upper case
builder.setCharAt(i,(char)(ch+('A'-'a')));
isLastSpace=false;
}
elseif(ch!='')
isLastSpace=false;
else
isLastSpace=true;
}
rentrn builder.toString();
}
public static void main(String[] args){
CaseConverter converter=new CaseConverter();
String str=converter.camelCase("thisisthesamplestring");
System.out.println(str);
}
}
Input: this is the
sample string
Output: This Is The Sample
String
How can create object array in java ----
[Bangladesh Power Development Board, Asst Eng., -2018]
Unlike traditional array
which store values like string, integer, Boolean, etc. array of objects stores
objects. The array elements store the location of reference variables of the
object
Syntax:
Class obj[]= new Class[array_length]
Example: To create
Array Of Objects
Step 1) Copy the following code into an editor
class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;
//obj[0] = new Account();
//obj[1] = new Account();
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
Example of array object
class Car {
private
String color;
public Car(String c) { //constructor
color=c;
}
public void setColor(String newColor)
{
color=newColor;
}
public String getColor()
{
return color;
}
public void honk()
{
System.out.println("Beep Beep!!!");
}
}
class MainClass {
public static void main(String
args[]) {
Car myCars[]=new Car[5];
int i;
for(i=0;i<3;i++)
myCars[i]=new
Car("Red");
myCars[3]=new
Car("Black");
myCars[4]=new
Car("White");
System.out.println(myCars[2].getColor());
myCars[2].setColor("Gray"); System.out.println(myCars[2].getColor()); //now the new color will be printed
for(i=0;i<5;i++)
{
System.out.print("My
"+myCars[i].getColor()+" honks: ");
myCars[i].honk();
}
}
}
Write a program – create a class name X(Power
generation) and there will be an constructor for assign the member value, day
as interger, generation as integer, supply as integer, storage as integer, and
create 7 object and call Power generation class from Main method.[BPDB-2018]
Answer:
class
Pow_gen{
int
day;
int gen;
int
supply;
int
storage;
Public
Pow_gen(int d, int g, int su)
{
Day=d;
Gen=g;
Supply=su;
}
Public int
storage()
{
return
gen-supply ;
}
}
An an is a binary number word where there is no cosecutive two 11. Write a program to find this.[EGCB-2018]
If there is more than 1 consecutive 1 then max output would be more than 1 like 2,3,4
First solution:-
importjava.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution{
public static voidmain(String[]args){
Scannerin=newScanner(System.in);
intn=in.nextInt();
intmax=0,count=0;
while(n>0){
if(n%2==1){
count++;
}else{
max=Math.max(count,max);
count=0;
}
n=n>>1;// same as n=n/2
}
System.out.println(Math.max(count,max));
}
}
Count number of binary
strings without consecutive 1’s
Given a positive integer N, count all possible
distinct binary strings of length N such that there are no consecutive 1’s.
Examples:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
This problem can be solved
using Dynamic Programming. Let a[i] be the number of binary strings of length i
which do not contain any two consecutive 1’s and which end in 0. Similarly, let
b[i] be the number of such strings which end in 1. We can append either 0 or 1
to a string ending in 0, but we can only append 0 to a string ending in 1. This
yields the recurrence relation:
a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1]
The base cases of above
recurrence are a[1] = b[1] = 1. The total number of strings of length i is just
a[i] + b[i].
Following is the implementation of above solution. In the following implementation, indexes start from 0. So a[i] represents the number of binary strings for input length i+1. Similarly, b[i] represents binary strings for input length i+1.
#include <iostream>
using namespace std;
int countStrings(int n)
{
int a[n], b[n];
a[0]
= b[0] = 1;
for (int i = 1; i < n; i++)
{
a[i]
= a[i-1] + b[i-1];
b[i]
= a[i-1];
}
return a[n-1] + b[n-1];
}
// Driver program to
test above functions
int main()
{
cout
<< countStrings(3) << endl;
return 0;
}
What is this pointer?
This pointer
refers to the current object of a class.
THIS keyword used as a pointer which differentiates between the current
object with the global object. Basically it refer to the current object.
Find the second largest element in the array,
without using library function or sort function [Dutch Bangla Bank
PO(software)]-2018
#include
<stdio.h>
#include
<limits.h>
void
print2largest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
if (arr[i] >
first)
{
second = first;
first = arr[i];
}
else
if
(arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second ==
INT_MIN)
printf("There is no second largest
element\n");
else
printf("The second largest element
is %d ", second);
}
int main()
{
int arr[100] ;
for(int i=0;i<=5;i++)
{
scanf("%d",&arr[i]);
}
print2largest(arr, 5);
return 0;
}
Question: Does
java support virtual functions?
Answer:
No java does not support virtual
functions direclty like in C++, but it supports using Abstract class and
interfaces
Question:
Describe what happens when an object is created in Java
Answer:
Several things happen in a particular
order to ensure the object is Constructed properly:
What is use in java instead of
friend function?
Using friend function you can access private members of
class. It can be used in C++ not in java.
There is no Friend function in java.
Java
does not have the friend keyword from C++. There is, however, a way to emulate
that; a way that actually gives a lot more precise control. Suppose that you
have classes A and B. B needs access to some private method or field in A.
Public class A {
private int privateInt = 31415;
public class SomePrivateMethods {
public int getSomethingPrivate() { return privateInt; }
private SomePrivateMethods() {} // no public constructor
}
Public void giveKeyTo(B other) {
other.receiveKey(newSomePrivateMethods());
}
}
Public class B {
Private A.SomePrivateMethods key;
Public void receiveKey(A.SomePrivateMethods key) {
this.key = key;
}
Public void usageExample() {
A anA = newA();
anA.giveKeyTo(this);
intfii = key.getSomethingPrivate();
System.out.println(fii);
}
}
The usageExample() shows how this works. The instance of B doesn't have access to the private fields or methods of an instance of A. But by calling the giveKeyTo(), class B can get access. No other class can get access to that method, since it a requires a valid B as an argument. The constructor is private.
The class B can then use any of the methods that are handed to it in the key. This, while clumsier to set up than the C++ friend keyword, is much more fine-grained. The class A can chose exactly which methods to expose to exactly which classes.
Now, in the above case A is granting access to all instances of B and instances of subclasses of B. If the latter is not desired, then the giveKeyTo() method can internally check the exact type of other with getClass(), and throw an exception if it is not precisely B.
How can create virtual constructor ?
C++ does not support virtual constructor but support virtual destructor.
how can use virtual function in java?
In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
importjava.util.*;
publicclassAnimal
{
publicvoid eat()
{
System.out.println("I eat like a generic Animal.");
}
publicstaticvoid main(String[] args)
{
List<Animal> animals = newLinkedList<Animal>();
animals.add(newAnimal());
animals.add(newFish());
animals.add(newGoldfish());
animals.add(newOtherAnimal());
for (AnimalcurrentAnimal : animals)
{
currentAnimal.eat();
}
}
}
classFishextendsAnimal
{
@Override
publicvoid eat()
{
System.out.println("I eat like a fish!");
}
}
classGoldfishextendsFish
{
@Override
publicvoid eat()
{
System.out.println("I eat like a goldfish!");
}
}
classOtherAnimalextendsAnimal {}
Output:
I eat like a generic Animal.
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.
Q8. Drawing interface from following diagram [DESCO BUET Asst. Eng 2016]
Code:-
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
font-family: Calibri, Helvetica, sans-serif;
background-color: pink;
}
.container {
padding: 40px;
background-color: lightblue;
}
input[type=text], input[type=password], textarea {
width: 100%;
padding: 10px;
margin: 3px 0 16px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: orange;
outline: none;
}
div {
padding: 6px 0;
}
hr {
border: .5px solid #f1f1f1;
margin-bottom: 20px;
}
.registerbtn {
background-color: #4CAF50;
color: white;
padding: 12px 16px;
margin: 6px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.6;
}
.registerbtn:hover {
opacity: 1;
}
</style>
</head>
<body>
<form>
<div class="container">
<center> <h1> Student Registeration Form</h1> </center>
<hr>
<label> Firstname </label>
<input type="text" name="firstname" placeholder= "Firstname" size="15" required />
<label> Middlename: </label>
<input type="text" name="middlename" placeholder="Middlename" size="15" required />
<label> Lastname: </label>
<input type="text" name="lastname" placeholder="Lastname" size="15"required />
<div>
<label>
Course :
</label>
<select>
<option value="Course">Course</option>
<option value="CSE">CSE</option>
<option value="ICT">ICT</option>
<option value="EEE">EEE</option>
<option value="ECE">ECE</option>
<option value="IT">IT</option>
</select>
</div>
<div>
<label>
Gender :
</label><br>
<input type="radio" value="Male" name="gender" checked > Male
<input type="radio" value="Female" name="gender"> Female
<input type="radio" value="Other" name="gender"> Other
</div>
<label>
Phone :
</label>
<input type="text" name="country code" placeholder="Country Code" value="+88" size="2"/>
Current Address :
<textarea cols="80" rows="5" placeholder="Current Address" value="address" required>
</textarea>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="registerbtn">Submit</button>
</form>
</body>
</html>
Now draw a interface of this system for
the user in a convenient way from where user get proper instruction.
Q. Write the output of the following program [DESCO BUET Asst. Eng 2016]
#include
<iostream>
#include<stdio.h>
#define MAX(A,B) ((A)>(B)) ? A:B
using namespace std;
int main(){
int i=1;
int j=2;
int val=max(++i,++j);
printf("%d",val);
}
OUTPUT:
3
Q. Write the output of the following program [DESCO
BUET Asst. Eng 2016]
#include
<iostream>
#include<stdio.h>
using namespace
std;
int sum(int
val){
static int myResult=0;
myResult += val;
return myResult;
}
int main(){
int i, value;
for(i=1;i<10;i++)
value=sum(i);
printf("%d",value);
}
OUTPUT
45
Write palindrome
program in java or c++ [Dutch bangle Bank -2017]
Java |
C++ |
ClassPartindome { public static void (String
args[]) ( int r, sum=0,
temp; int n=454; temp=n; while (n > 0){ ( r=n % 10, //getting
remainder sum=(sum * 10)
+ r; n = n / 10; } if (temp==sum) System.out.println
("palindrome number "); else System.out.println("not
palindrome“); } } |
#include<iostream> using
namespace std ; int main ( ) { int
r,sum=0,temp; int n; std::cin>> n; temp=n; while(n>0){ r=n/10; sum=(sum*10)+r; n=n / 10 ; if(temp==sum) cout<<"palindrome
number "; else cout<<"not
palindrome"; return 0; } |
What is the difference among
String, StringBuffer and StringBuilder? [Dutch Bangla Bank-2017]
Mutability
Difference:
String is immutable, if you try
to alter their values, another object gets created, whereas StringBuffer and
StringBuilder are mutable so they can change their values.
Thread-Safety
Difference:
The difference between
StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the
appEcation needs to be run only in a single thread then it is better to use
StringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:
If your string is not going to
change use a String class because a String object is immutable.
If your string can change
(example: lots of logic and operations in the construction of the string) and
will only be accessed from a single thread, using a StringBuilder is good
enough.
If your string can change, and
will be accessed from multiple threads, use a StringBuffer because StringBuffer
is synchronous so you have thread-safety.
Java Programming:
Write a class
named Bicycle and create a constructor of its and initialize the class member
names cadense as Integer, gear as Integer speed as Integer. Write another class
MountainBike and create also a constructor of its and add this field seatHeight
as Integer and a method to set its from this class and extend Bicycle class. [DESCOBUET Asst. Eng 2016]
public class Bicycle {
// the
Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the
Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int
startGear) {
gear =
startGear;
cadence =
startCadence;
speed =
startSpeed;
}
// the
Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void
applyBrake(int decrement) {
speed -=
decrement;
}
public void speedUp(int increment) {
speed +=
increment;
}
}
public class MountainBike extends Bicycle {
// the
MountainBike subclass has one field
public int seatHeight;
// the
MountainBike subclass has one constructor
public MountainBike(int startHeight, int startCadence, int
startSpeed, int
startGear) {
super(startCadence, startSpeed, startGear);
seatHeight =
startHeight;
}
// the
MountainBike subclass has one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike inherits all the fields and methods of
Bicycle and adds the fieldseatHeight and a method to set it (mountain bikes
have seats that can be moved upand down as the terrain demands).
Write a program
to calculate the two string is meta string or not ?
#include<iostream>
using namespace
std;
bool areMetaStrings(string str1, string str2)
{
int len1 =
str1.length();
int len2 =
str2.length();
if (len1 != len2)
returnfalse;
int prev = -1, curr = -1;
int count = 0;
for (int i=0;
i<len1; i++)
{
if (str1[i] != str2[i])
{
count++;
if (count > 2)
returnfalse;
prev =
curr;
curr =
i;
}
}
return (count == 2
&& str1[prev] == str2[curr] &&
str1[curr] == str2[prev]);
}
int main()
{
string str1 =
"converse";
string str2 = "conserve";
areMetaStrings(str1,str2) ? cout << "Yes" : cout
<< "No";
return 0;
}
Count number of bits to
be flipped to convert A to B
Example :
Input : a = 10, b = 20
Output : 4
Binary representation of a is 00001010
Binary representation of b is 00010100
We need to flip highlighted four bits in a
to make it b.
Input : a = 7, b = 10
Output : 3
Binary representation of a is 00000111
Binary representation of b is 00001010
We need to flip highlighted three bits in a
to make it b.
1. Calculate XOR of A and B.
a_xor_b = A ^ B
2. Count the set bits in the above
calculated XOR result.
countSetBits(a_xor_b)
#include <iostream>
using namespace std;
int countSetBits(int n)
{
int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
int FlippedCount(int a, int
b)
{
return countSetBits(a^b);
}
int main()
{
int a = 3;
int b = 15;
cout << FlippedCount(a,
b)<<endl;
return 0;
}
what’s the diamond problem, and how can it
be avoided?
Taking a look at the
graphic below helps in explaining the diamond problem.
Suppose we have 2
classes B and C that derive from the same class – in our example above it would
be class A. We also have class D that derives from both B and C by using
multiple inheritance. You can see in the figure above that the classes
essentially form the shape of a diamond – which is why this problem is called
the diamond problem. Now, let’s take the graphic above and make it more
concrete by translating it into actual code:
class Animal { /* ... */
}; // base class
{
int weight;
public:
int getWeight() { return
weight;};
};
class Tiger : public
Animal { /* ... */ };
class Lion : public
Animal { /* ... */ }
class Liger : public
Tiger, public Lion { /* ... */ };
In
the code above, we’ve given a more concrete example of the diamond problem. The
Animal class corresponds to the topmost class in the hierarchy (A in our
graphic above), Tiger and Lion respectively correspond to B and C in the
graphic, and the Liger class corresponds to D.
Q. there is one circle class and one cylinder class.
circle class has an area function. Cylinder class has to calculate the circle
area at the base and height of its own. Cylinder area= circle area*height. Use
inheritance to calculate area of cylinder. [PO Dutch bangle bank-2016]
Class circle
{
Private double radius;
Public circle()
{
Radious=2.0;
}
Double get_area()
{
Return
radius*radius*3.1416;
}
}
Class Cylinder extends
circle
{
Public double
get_volume(double height )
{
Return
get_area()*height;
}
}
Program to sort
string in dictionary order [AP in education
ministry -2014]
#include<stdio.h>
#include <string.h>
int main()
{
int i, j;
char str[10][50], temp[50];
printf("Enter 5 words:\n");
for(i=0; i<5; ++i)
scanf("%s[^\n]",str[i]);
for(i=0; i<4; ++i)
for(j=i+1; j<5 ; ++j)
{
if(strcmp(str[i], str[j])>0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
printf("\nIn
lexicographical order: \n");
for(i=0; i<5; ++i)
{
puts(str[i]);
}
return 0;
}
·
Write a java program based
on following conditions: There is one Circle class and one Cylinder Class.
Circle class has an area function. Cylinder Class has to calculate the circle
area at the base and height of its own (Cylinder area= Circle area*height). Use
inheritance to calculate area of Cylinder. [Dutch
Bangla Bank-2017]
Solution:
public class
CircleExample{
public double area, public
double redius;
public double getArea(){
area=3.14l6*redius*redius;
return area;
}
public class Cylinder
extends CircleExample{
public static void
main(String[] args) {
double
height=l0,cylinderArea,
CircleExample ce=new
CircleExample();
ce.redius=5,
cylinderArea=ce.getArea()*height;
System.out.println("Cylinder
Area: "+cylinderArea);
}
}
Why Java is Platform Independent?
Platform independence is one of the main advantages of Java. In another words,
java is portable because the same java program can be executed in multiple
platforms without making any changes in the source code. You just need to write
the java code for one platform and the same program will run in any platforms.
But how does Java make this possible?
As we discussed early, first the Java code is compiled by the Java compiler and generates the bytecode. This bytecode will be stored in class files. Java Virtual Machine (JVM) is unique for each platform. Though JVM is unique for each platform, all interpret the same bytecode and convert it into machine code required for its own platform and this machine code will be directly executed by the machine in which java program runs. This makes Java platform independent and portable.
Let’s make it more clear with the help of the following diagram. Here the same compiled Java bytecode is interpreted by two different JVMS to make it run in Windows and Linux platforms.
Why Java is Secure?
As you have noticed in the prior session “Java
Runtime Environment (JRE) and Java Architecture in Detail”, the byte code is
inspected carefully before execution by Java Runtime Environment (JRE). This is
mainly done by the “Class loader” and “Byte code verifier”. Hence a high level
of security is achieved.
Method to find out how
many times an object has been instantiated in java. [BUET ad-2015]
package com.instance.main;
import com.instance.target.Clasa;
publicclassTest{
publicstaticvoid main(String[] args){
Clasa targetClass;
Object[] object=newObject[10];
for(int i=0;i<object.length;i++){
object[i]=newClasa();
}
System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa.getNumberOfInstatiateObj());
for(int i=0;i<object.length;i++){
if(i==8){
object[i]=object[i+1];
object[i+1]=null;
System.runFinalization();
System.gc();
}
}
}
}
just put the above code beneath the main method and also you have to modify your Clasa code from the below code
package com.instance.target;
class Clasa {
privatestaticint nbInstances =0;
publicClasa(){
nbInstances++;
}
publicint getNo(){
return nbInstances;
}
publicvoid finalize(){
nbInstances --;
System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances );
}
}
How
to Count the Number of Objects in a Class in Java?
package students;
class
Students
{
public String
name;
public int
age;
public static int
numberofobjects=0;
Students (String
name, int age)
{
this.name= name;
this.age=
age;
numberofobjects++;
}
}
create
our class constructor.
package students;
class studentsdemo
{
public static void
main(String[]args)
{
Students student1= new
Students("Michelle", 7);
Students student2= new
Students("Daniel", 8);
Students student3= new
Students("Vanessa", 9);
Students student4= new
Students("Ryan", 8);
System.out.println
("There are " + Students.numberofobjects + " objects in this
class");
}
}
So we create a test class
named studentsdemo. create 4 objects of
the Students class, student1, student2, student3, and student4
Java Output
There are 4 objects in this
class
Or
public class
Number_Objects
{
static int count=0;
Number_Objects()
{
count++;
}
public static void
main(String[] args)
{
Number_Objects obj1 = new
Number_Objects();
Number_Objects obj2 = new
Number_Objects();
Number_Objects obj3 = new
Number_Objects();
Number_Objects obj4 = new
Number_Objects();
System.out.println("Number of
objects created:"+count);
}
}
Components
of .Net Framework[Sonli Bank Asst. Programmer-2016, Agrani Bank(Senior
Officer-IT-2018)]
|
|
There are many articles are available in the web on this
topic; I just want to add one more article over the web by explaining Components
of .Net Framework. Components of .Net Framework Net Framework is a platform that provides tools and
technologies to develop Windows, Web and Enterprise applications. It mainly
contains two components, 1. Common
Language Runtime (CLR) 2. .Net
Framework Class Library. 1. Common Language Runtime (CLR) There are currently over
15 language compilers being built by Microsoft and other companies also
producing the code that will execute under CLR. 1. Windows
Application. 2. Console Application 3. Web Application. 4. XML Web Services. 5. Windows
Services. In short, developers
just need to import the BCL in their language code and use its predefined
methods and properties to implement common and complex functions like reading
and writing to file, graphic rendering, database interaction, and XML
document manipulation. What is MVC architecture ? Model View Controller or MVC as
it is popularly called, is a software design pattern for developing web
applications. A Model View Controller pattern is made up of the following
three parts: ·
Model - The lowest level of the pattern which is responsible
for maintaining data. ·
View - This is responsible for displaying all or a portion of
the data to the user. ·
Controller - Software Code that controls the interactions between
the Model and View. MVC is popular as it isolates the
application logic from the user interface layer and supports separation of
concerns. Here the Controller receives all requests for the application and
then works with the Model to prepare any data needed by the View. The View
then uses the data prepared by the Controller to generate a final presentable
response. The MVC abstraction can be graphically represented as follows.
The
model The model is responsible for
managing the data of the application. It responds to the request from the
view and it also responds to instructions from the controller to update
itself. The
view A presentation of data in a
particular format, triggered by a controller's decision to present the data.
They are script based templating systems like JSP, ASP, PHP and very easy to
integrate with AJAX technology. The
controller The controller is responsible for
responding to user input and perform interactions on the data model objects.
The controller receives the input, it validates the input and then performs
the business operation that modifies the state of the data model. Struts2 is a MVC based framework.
In the coming chapters, let us see how we can use the MVC methodology within
Struts2. MVC=model
control view advantage ;- 1)
Work with class and object. 2)
More security 3)
Intelligence 4)
Frame work design according to the MVC. |
Copy Constructor in C++ [BUET M.SC Admission -2015]
What is a copy constructor?
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
ClassName (const ClassName &old_obj);
Following is a simple example of copy constructor.
|
When to use
Abstract Methods & Abstract Class?
•
Abstract methods are usually declared where two or more subclasses are expected
to fulfill a similar role in different ways through different implementations •
These subclasses extend the same Abstract class and provide different
implementations for the abstract methods • Use abstract classes to define broad
types of behaviors at the top of an object-oriented programming class
hierarchy, and use its subclasses to provide implementation details of the
abstract class.
Interface vs. Abstract Class.
Aptitude test – [Madrasha
Education Board(Assistant Programmer-2018), BUET]
1.Read multiline input from text file and write in another
file the following work
a.
Each input line of the
file.
b.
Converts lower case to
upper case and vice versa.
c.
Sum of the digit.
Solution of the problem:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
char c;
char d='\n';
int sum=0,c1=1;
FILE *f1,*f2;
f1 = fopen("input.txt", "rb");
f2 = fopen("output.txt", "wb");
while ((c = fgetc(f1))
!= EOF)
{
if(c>=65 && c<=90)
c=c+32;
else if (c>=97 &&c<=122)
c=c-32;
else if(c>=48 && c<=57)
sum=sum+(c-48);
else if (c=='\n')
c1++;
fprintf (f2, "%c",c);
}
fprintf (f2, " %c",d);
fprintf (f2, "\n The sumation of digit is = %d ",
sum);
fprintf (f2, " Total line= %d",c1);
fclose(f1);
fclose(f2);
return 0;
}
2.Develop a web site by the following instruction
a. name of the oraginzation top of
the site as well as logo of the organization.
b. put pull link right site on the
web page where clike go throw next page
c. bullet mark
information
Consider the following code segment: [BUET
Academic OOP-2018, Bangladesh Power Development Board 2019]
Public class main {
Public static void main (string[] args) {
int a = minmax(“min”,2,1,6,4,5); //a=1
int b=minmax(“min”,3,0,6); //b=0
int c=minmax(“max”,1,2,6,5);// c=6
int d=minmax(“max”,1,3,7); //d=7
}
}
Solution:-
public
class TestMain {
private static int minmax(String operation, int...
variableLeanthArray) {
int result =
variableLeanthArray;
switch (operation) {
case
"min":
for (int i : variableLeanthArray) {
if(i<result)
result = i;
}
break;
case
"maxt":
for
(int i : variableLeanthArray) {
if(i>result)
result
= i;
}
break;
default:
break;
}
return
result;
}
public static void main(String[]
args) {
int a =
minmax("min", 2, 1, 6, 4, 5);
int b = minmax
("min", 3, 0, 6);
int c = minmax
("max", 1, 2, 6, 5);
int d = minmax
("max", 1, 3, 7);
System.out.println(a
+ " " + b + " " + " " + c + " " + d);
}
}
What is the signature of Java main method? Briefly describe the
significance of each term.
classNewClass{
publicstaticvoid main(String a){
System.out.print("Hello");
}
}
When I'm trying to execute
above code, then it shows an error, main method not found.
But when I changed public static void main(String a)
to public static void main(String... a)
or public static void main(String a[])
. Then, it works..!!
So, My question is how
many different ways we can write legal main method
signature and what this signature public static void main(String... a)
means ?
Answer:
-
Valid
Signature of main method in Java
main method is a standard method and has pre specified signature,
if you change the signature of main method JVM will not be able to locate main
method will throw Exception at runtime as shown in above example. main method
is public, static and void and accept an String[] as argument and from Java 5
onwards it can also accept variable arguments instead of array. following
signatures are valid main method signature in Java :
public static void main(String args[]) {}
public static void main(String[] args){}
public static void main(String... args){}
You can also use certain modifier
like final, synchronized and strictfp along with main
method in Java.
The points to remember is -
·
The keywords public
and static are interchangeable but mandatory.
·
The parameter of the
main method can take the var-args syntax.
·
The name can be
anything..!
Why main method is public static and void in Java?
This is very famous core Java interview question, and appeared on
many fresher and experience level interviews. Though ever java programmer uses
main method not every one is familiar with reason why main is static or why
main is public in Java. Here are few reasons which make sense to me to think of
Why main is public, static and void in java
main method in Java is public so that its visible to every other
class, even which are not part of its package. if its not public JVM classes
might not able to access it.
main method is static in Java, so that it can be called without
creating any instance. While JVM tries to execute Java program it doesn't know
how to create instance of main class as there is no standard constructor
is defined for main class.
Write Java code to exchange two integer variables using a method
named swap. The main method will call the swap method and the changes inside
the swap method must be visible to the main method. You also need to write the
main method?
publicstaticint getItself(int itself,int dummy)
{
return itself;
}
publicstaticvoid main(String[] args)
{
int a =10;
int b =20;
a = getItself(b, b = a);
}
Write two different ways to create Threads in Java. Which one is
better and why?
Threading is a facility to allow multiple tasks to run concurrently
within a single process. Threads are independent, concurrent execution through
a program, and each thread has its own stack.
In Java threads can be implemented in two ways.
1) by Extending Thread Class
e.g.
class ThreadDemo extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
ThreadDemo t1=new ThreadDemo();
t1.start();
}
}
Output:thread is running...
2) by Implementing Runnable Interface
class RunnableDemo implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void
main(String args[]){
RunnableDemo rd=new RunnableDemo();
Thread t1 =new
Thread(rd);
t1.start();
}
}
Output:thread is running...
difference between
extends thread and implements runnable
v
The limitation with
"extends Thread" approach is that if you extend Thread, you can not
extend other class . Java does not support multiple inheritance.
While with implement runnable we can extend other class
also.
v
In "implements
Runnable" , we are creating a different Runnable class for a specific
task. It gives us the freedom to reuse the specific behavior task whenever
required.
"extends Thread" contains both thread and job
specific behavior code. Hence once thread completes execution , it can not be
restart again.
v
"implements
Runnable" makes the code loosely-coupled and easier to read .Because the
code is split into two classes . Thread class for the thread specific code and
your Runnable implementation class for your task that should be run by a thread
code.
"extends Thread" makes the code tightly coupled
. Single class contains the thread code as well as the task that needs to be
done by the thread.
there are many other difference also.
As per he above difference second approach has many advantages
over the first approach so second approach is preferable.
Write
Java code to do the following:
Declare
a static nested class Inner1 of an outer class Outer1 and create an object of Inner 1
class inside NestedDemo class's main method.
Nested Classes in Java
In java, it is possible to
define a class within another class, such classes are known as nested classes.
They enable you to logically group classes that are only used in one place,
thus this increases the use of encapsulation, and create more readable and maintainable code.
§ The
scope of a nested class is bounded by the scope of its enclosing class. Thus in
above example, class NestedClass does not exist independently of
class OuterClass.
§ A
nested class has access to the members, including private members, of the class
in which it is nested. However, reverse is not true i.e. the enclosing class
does not have access to the members of the nested class.
§ A
nested class is also a member of its enclosing class.
§ As a
member of its enclosing class, a nested class can be declared private, public, protected,
or package private(default).
§ Nested
classes are divided into two categories:
1. static nested class : Nested
classes that are declared staticare called static nested classes.
2. inner class : An
inner class is a non-static nested class.
Syntax:
class OuterClass
{...
class NestedClass
{ ...
}
}
class OuterClass
{
staticint outer_x = 10;
//
instance(non-static) member
int outer_y = 20;
private
static int outer_private = 30;
staticclass StaticNestedClass
{
void display()
{
//
can access static member of outer class
System.out.println("outer_x
= " + outer_x);
// can access display
private static member of outer
System.out.println("outer_private
= " + outer_private); // The following statement will give
compilation error
//
as static nested class cannot directly access non-static membera
//
System.out.println("outer_y = " + outer_y);
}
}
}
// Driver class
publicclass StaticNestedClassDemo
{
publicstaticvoid main(String[] args)
{
//
accessing a static nested class
OuterClass.StaticNestedClass
nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Inner classes
To instantiate an inner
class, you must first instantiate the outer class. Then, create the inner
object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of
inner classes :
Declare an inner class Inner2 of an outer
class Outer2
and create an object of Inner2 class inside NestedDemo class's main method.
class Outer2
{
//
static member
static int outer_x = 10;
//
instance(non-static) member
int outer_y = 20;
//
private member
private int outer_private = 30;
//
inner class
classInner2
{
void display()
{
//
can access static member of outer class
System.out.println("outer_x
= " + outer_x);
//
can also access non-static member of outer class
System.out.println("outer_y
= " + outer_y);
//
can also access private member of outer class
System.out.println("outer_private
= " + outer_private);
}
}
}
// Driver class
public classNestedDemo
{
public static void main(String[] args)
{
//
accessing an inner class
Outer2
outerObject = new Outer2();
Outer2.Inner2
innerObject = outerObject.new Inner2();
innerObject.display();
}
}
There are four kinds of nested class
in Java. In brief, they are:
·
static
class: declared as a static member of another class
·
inner
class: declared as an instance member of another
class
·
local
inner class: declared inside an instance method of another
class
·
anonymous
inner class: like a local inner
class, but written as an expression which returns a one-off object
Static
Classes
Static classes are the easiest kind to
understand because they have nothing to do with instances of the containing
class.
A static class is a class declared as a static
member of another class. Just like other static members, such a class is really
just a hanger on that uses the containing class as its namespace, e.g. the class Goat declared as a static member
of class Rhino in the
package pizza is
known by the name pizza.Rhino.Goat.
package pizza;
publicclassRhino {
...
publicstaticclassGoat {
...
}
}
Frankly, static classes are a pretty worthless
feature because classes are already divided into namespaces by packages. The
only real conceivable reason to create a static class is that such a class has
access to its containing class's private static members, but I find this to be
a pretty lame justification for the static class feature to exist.
Inner
Classes
An inner class is a class declared as a
non-static member of another class:
package pizza;
publicclassRhino {
publicclassGoat {
...
}
privatevoid
jerry() {
Goat g = newGoat();
}
}
Like with a static class, the inner class is
known as qualified by its containing class name, pizza.Rhino.Goat, but inside the containing class, it can be
known by its simple name. However, every instance of an inner class is tied to
a particular instance of its containing class: above, the Goatcreated in jerry, is implicitly tied to
the Rhino instance this in jerry. Otherwise, we make the
associated Rhino instance
explicit when we instantiate Goat:
Rhino rhino = newRhino();
Rhino.Goat goat = rhino.newGoat();
Local
Inner Classes
A local inner class is a class declared in the
body of a method. Such a class is only known within its containing method, so
it can only be instantiated and have its members accessed within its containing
method. The gain is that a local inner class instance is tied to and can access
the final local variables of its containing method. When the instance uses a
final local of its containing method, the variable retains the value it held at
the time of the instance's creation, even if the variable has gone out of scope
(this is effectively Java's crude, limited version of closures).
Anonymous
Inner Classes
An anonymous inner class is a syntactically
convenient way of writing a local inner class. Most commonly, a local inner
class is instantiated at most just once each time its containing method is run.
It would be nice, then, if we could combine the local inner class definition
and its single instantiation into one convenient syntax form, and it would also
be nice if we didn't have to think up a name for the class (the fewer unhelpful
names your code contains, the better). An anonymous inner class allows both
these things:
new *ParentClassName*(*constructorArgs*) {*members*}
This is an expression returning a new instance
of an unnamed class which extends ParentClassName.
You cannot supply your own constructor; rather, one is implicitly supplied
which simply calls the super constructor, so the arguments supplied must fit
the super constructor. (If the parent contains multiple constructors, the
“simplest” one is called, “simplest” as determined by a rather complex set of
rules not worth bothering to learn in detail--just pay attention to what NetBeans
or Eclipse tell you.)
Alternatively, you can specify an interface to
implement:
new *InterfaceName*() {*members*}
Why Use
Nested Classes?
According to Oracle documentation there're several reasons
• It is a way of logically grouping classes that are only used in
one place: If a class is useful to only one other class, then it is logical to
embed it in that class and keep the two together. Nesting such "helper
classes" makes their package more streamlined.
• It increases encapsulation: Consider two top-level classes, A
and B, where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared private
and B can access them. In addition, B itself can be hidden from the outside
world.
• It can lead to more readable and maintainable code: Nesting
small classes within top-level classes places the code closer to where it is
used.
Nested Classes in Java
Difference between static and inner(non-static
nested) classes
Static nested classes do not directly have
access to other members(non-static variables and methods) of the enclosing
class because as it is static, it must access the non-static members of its
enclosing class through an object. That is, it cannot refer to non-static
members of its enclosing class directly. Because of this restriction, static
nested classes are seldom used.
Non-static nested classes (inner classes) has
access to all members(static and non-static variables and methods, including
private) of its outer class and may refer to them directly in the same way that
other non-static members of the outer class do.
Write Java code to do the following: [BUET OOP-2018]
(i)Declare a static nested class Inner1 of
an outer class Outer1 and create an object of Inner
1 class inside NestedDemo class's main method.
Solution: (i) by Static nested class
Outer1.inner1.nestedObject
= new Outer1.inner1();// accessing a static nested class
Class Outer1
{
static int outer_x =
10; // static member
int outer_y = 20; // instance(non-static) member
private static int outer_private = 30; // private member
static class inner1 // static nested class
{
void display()
{
System.out.println("outer_x = " + outer_x); // can
access static member of outer
System.out.println("outer_private = " + outer_private);
// can access display private static member of outer class
// System.out.println("outer_y = " + outer_y); // as
static nested class cannot directly access non-static member
}
}
}
public class
Static NestedDemo// Driver class
{
public static void main(String[] args)
{
Outer1.inner1.nestedObject
= new Outer1.inner1(); // accessing a static nested class
nestedObject.display();
}
}
Output:
outer_x = 10
outer_private = 30
(ii) Declare an inner class Inner2 of an outer class Outer2 and
create an object of Inner2 class inside NestedDemo class's main method.
Solution (ii) by inner class
Outer2.Inner2 innerObject = outer2.new Inner2();
class Outer2
{
static int
outer_x = 10; // static member
int outer_y
= 20; // instance(non-static) member
private int
outer_private = 30; // private member
class Inner2 // inner class
{
void display()
{
System.out.println("outer_x =
" + outer_x); // can access static member of outer class
System.out.println("outer_y = " + outer_y); // can also
access non-static member of outer
class
System.out.println("outer_private
= " + outer_private); // can also access private member of outer class
}
}
}
// Driver class
public classNestedDemo
{
public
static void main(String[] args)
{
// Outer2
outerObject = new Outer2();// accessing an inner class
Outer2.Inner2 innerObject = outer2.new Inner2();
innerObject.display();
}
}
Abstraction in Java
Abstraction is
a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where you type the text
and send the message. You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead
of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1.
Abstract class (0 to 100%)
2.
Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs
to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An
abstract class must be declared with an abstract keyword.
o It
can have abstract and non-abstract methods.
o It
cannot be instantiated.
o It
can have constructors and static methods also.
o It
can have final methods which will force the subclass not to change the body of
the method.
Example of abstract class
1.
abstract class A{}
Abstract Method in Java
A method which is declared as abstract and does not have
implementation is known as an abstract method.
Example of abstract method
1.
abstract void printStatus();//no method body and abstract
Example of Abstract class that has an
abstract method
In this example, Bike is an abstract class that contains
only one abstract method run. Its implementation is provided by the Honda
class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output
running safely
Understanding the real scenario of Abstract class
In this example, Shape is the abstract class, and its
implementation is provided by the Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which
is hidden to the end user), and an object of the implementation class is
provided by the factory
method.
A factory
method is a method that returns
the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle
class, draw() method of Rectangle class will be invoked.
File:
TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
Output
drawing circle
Another example of Abstract class in java
File: TestBank.java
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Output
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class having constructor, data
member and methods
An abstract class can have a data member, abstract method,
method body (non-abstract method), constructor, and even main() method.
File:
TestAbstraction2.java
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output
bike is created
running safely..
gear changed
class Bike12{
abstract void run();
}
Output
compile time error
Another real scenario of abstract class
The abstract class can also be used to provide some
implementation of the interface. In such case, the end user may not be forced
to override all the methods of the interface.
Note: If you are beginner to
java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I am a
I am b
I am c
I am d
What are the restrictions to classes that extend abstract
class?Explain both with short code examples. [BUET OOP]
Abstract method restriction control
for derived classes
Is it possible for an abstract base class to
have abstract methods where only certain derived classes have access to certain
abstract methods? What I'm trying to do is limit possible methods being able to
be called from different inherited classes. Here is an example of my question:
publicabstractFoo
{ ...
publicabstractvoid fooMethod1(int num1);
publicabstractvoid fooMethod2(int num2);
}
publicBar1extendsFoo// This class shouldn't be able to access fooMethod2()
{ ...
@Override
publicvoid fooMethod1(int num1)
{
System.out.println((num1 * 5));
}
}
publicBar2extendsFoo// This class has no restrictions
{
...
@Override
publicvoid fooMethod1(int num1)
{
System.out.println((num1 * 10));
}
@Override
publicvoid fooMethod2(int num2)
{
System.out.println((num2 * 5));
}
There are few things we need to keep in mind
when working with abstract methods and abstract classes.
The rules for abstract methods and abstract
classes are:
A class can be marked as abstract with out
containing any abstract method. But if a class has even one abstract method,
then the class has to be an abstract class.
abstract class A
{
//
Valid, even with out any abstract methods
}
class B // Invalid, class B should be abstract,
since it has abstract method.
{
abstract void method1();
}
An abstract class can have one or more
abstract methods.
abstract class C
{
abstract void method1();
abstract double method2(int x, int
y);
abstract boolean method3(char z);
}
An abstract class can have both abstract and non abstract (or
concrete) method.
abstract class D
{
void method1()
{
System.out.println("I am a concrete method");
}
abstract double method2(int x, int y);
int method3(double z)
{
System.out.println("I am also a concrete method");
}
abstract boolean method4(char z);
}
The abstract method should not have method body. Even empty
flower braces { } are not allowed.
abstract class A
{
abstract void method1(); // Valid
abstract void method2() {} // Invalid - since it has method body
}
Any sub-class extending from an abstract class should either
implement all the abstract methods of the super-class or the sub-class itself
should be marked as abstract.
abstract class A
{
abstract void method1();
abstract void method2();
}
class B extends A
{
//
Invalid since B does not implement the abstract methods
}
abstract class C extends
A
{
//
Valid since C is marked as abstract, even though the abstract methods are not
implemented,
}
class D extends A
{
void method1()
{
System.out.println("Method1 implemented here.");
}
//
Invalid, class D should be marked as abstract, since method2 is not
implemented.
}
abstract class E extends A
{
void method1()
{
System.out.println("Method1 implemented here.");
}
//
Even though method2 is not implemented, class D is marked as abstract, so it is
Valid.
}
class F extends A
{
//
Valid since both methods are implemented here.
void method1()
{
System.out.println("Method1 implemented here.");
}
void method2()
{
System.out.println("Method2 implemented
here.");
}
}
If an abstract class contains multiple
methods, it is not necessary that all the methods of the abstract class are
implemented in the immediate sub-class. Few of them can be implemented in
sub-sub-classes or any where else in the sub-class hierarchy. But for a class
to be concrete, all the abstract methods in its super-class must be
implemented. [BUET OOP-2018]
abstract class X
{
abstract void method1();
abstract void method2();
}
abstract class Y extends X
{
void method1()
{
System.out.println("Method1 implemented here.");
}
}
class Z extends Y
{
void method2()
{
System.out.println("Method2 implemented here.");
}
}
It is not necessary to add the abstract methods only in the
super most class, we can add more abstract methods in the sub-classes.
abstract class X
{
abstract void method1();
}
abstract class Y extends X
{
abstract void method2();
}
class Z extends Y
{
void method1()
{
System.out.println("Method1 from class X implemented here.");
}
void method2()
{
System.out.println("Method1 from class Y implemented here.");
}
}
What is the
need of abstract classes in java? How they differ with Interfaces? Where do
Java developers actually use abstract classes & interfaces?
Exactly. Abstract
classes only say what to do not how to do. Each class that extends abstract
class must implement the unimplemented(methods whose body is not provided in
abstract class) methods of abstract class.
·
Methods of Interfaces
cannot have implementations. In other words, they can have only abstract or
non-concrete methods. Abstract classes can have both abstract methods and
concrete methods.
·
Interfaces can contain
only final variables(by default all variables are final). There may be final
variables in abstract classes.
·
Methods of interface
are public by default. Methods of abstract class can have modifiers such as
public, private..
·
Interface cannot
provide any code at all. Abstract class can provide complete code, default
code, and/or stubs that have to be overwritten.
·
Interface can extend
another interface only but cannot extend any type of class. Abstract class can
extend another java class, implement multiple java interfaces and extend only
one abstract class.
·
Interface is
absolutely abstract and cannot be instantiated. Abstract class cannot be
instantiated but can be invoked if main exists.

public interface A {
default void f (){
System.out.println("A`s f ");
}
}
public interface B {
default void f (){
System.out.println("B`s f ");
}
}
public class C implements A, B {
// To fix that, in C, we have
to resolve it manually by overriding the conflicting method f()
public void foo(){
A.super.foo();
}
}
Another solution
public class C
implements A, B {
public void f ( ) default A.f;
}
Write minimum code in class c2 for successful compilation.
You can't define c2 as abstract.
interface i1 {
default void fl()
{ }
Void f2();
}
interface i2 {
void f3();
void f4();
}
abstract class C1 implements i1 {
abstract void f5();
final void f6() {
}
}
class C2 extends C1 implements i2 {
f5(){ // f5() have to describe
}
f2() { … f2() have to describe because
implement interface i1
}
f3() {……..// f3() have to describe
because implement interface i2
}
f4(){……..// f4() have to describe
because implement interface i2
}
}
What do you mean by auto-boxing and
auto-unboxing? When you shouldn't use them? Explain both with short code
examples. [BUET OOP-2018]
Autoboxing and Unboxing in Java
Autoboxing: Converting a
primitive value into an object of the corresponding wrapper class is called
autoboxing. For example, converting int to Integer class. The Java compiler
applies autoboxing when a primitive value is:
Ø Passed as a parameter
to a method that expects an object of the corresponding wrapper class.
Ø Assigned to a variable
of the corresponding wrapper class.
Unboxing: Converting an object
of a wrapper type to its corresponding primitive value is called unboxing. For
example conversion of Integerto int. The Java compiler applies unboxing when an
object of a wrapper class is:
Ø Passed as a parameter
to a method that expects a value of the corresponding primitive type.
Ø Assigned to a variable
of the corresponding primitive type.
Advantages of
Autoboxing / Unboxing:
Ø Autoboxing and unboxing
lets developers write cleaner code, making it easier to read.
Ø The technique let us
use primitive types and Wrapper class objects interchangeably and we do not
need to perform any typecasting explicitly.
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its
equivalent Wrapper type is known as boxing and opposite operation is known as
unboxing. This is the new feature of Java5. So java programmer doesn't need to
write the conversion code.
Advantage of Autoboxing
and Unboxing:
No need of conversion between primitives and Wrappers manually
so less coding is required.
imple Example of Autoboxing in java:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new
Integer(a);//Boxing
Integer
a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
Output:50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into
corresponding primitive type, is known as Unboxing. Let's see the example of
unboxing:
class UnboxingExample1{
public static void main(String args[]){
Integer i=new
Integer(50);
int a=i;
System.out.println(a);
}
}
Output:50
Autoboxing and Unboxing with comparison operators
Autoboxing can be performed with comparison operators. Let's see
the example of boxing with comparison operator:
class UnboxingExample2{
public static void main(String args[]){
Integer i=new Integer(50);
if(i<100){ //unboxing internally
System.out.println(i);
}
}
}
Output:50
Autoboxing and Unboxing with method overloading
In method overloading, boxing and unboxing can be performed. There
are some rules for method overloading with boxing:
Widening beats
boxing
Widening beats
varargs
Boxing beats
varargs
1) Example of Autoboxing where widening beats boxing
If there is possibility of widening and boxing, widening beats
boxing.
class Boxing1{
static void m(int
i){System.out.println("int");}
static void m(Integer
i){System.out.println("Integer");}
public static void main(String args[]){
short s=30;
m(s);
}
}
Output:int
2) Example of Autoboxing where widening beats varargs
If there is possibility of widening and varargs, widening beats
var-args.
class Boxing2{
static void m(int i, int
i2){System.out.println("int int");}
static void m(Integer...
i){System.out.println("Integer...");}
public static void main(String
args[]){
short s1=30,s2=40;
m(s1,s2);
}
}
Output:int int
3) Example of Autoboxing where boxing beats varargs
Let's see the program where boxing beats variable argument:
class Boxing3{
static void m(Integer
i){System.out.println("Integer");}
static void m(Integer...
i){System.out.println("Integer...");}
public static void
main(String args[]){
int a=30;
m(a);
}
}
Output:Integer
Method overloading with Widening and Boxing
Widening and Boxing can't be performed as given below:
class Boxing4{
static void m(Long
l){System.out.println("Long");}
public static void
main(String args[]){
int a=30;
m(a);
}
}
Output:Compile Time
Error
Consider following
code segment [BUET- OOP-2018]
public class Fruit {
private String name;
private int quantity;
}
public class Fruit {
private String name;
private String description;
private int imgBackground;
private int imgIcon;
private int quantity;
// Valores accesibles estáticamente
public static final int LIMIT_QUANTITY =
10;
public static final int RESET_VALUE_QUANTITY = 0;
public
Fruit() {
}
public Fruit(String name, String
description, int imgBackground, int imgIcon, int quantity) {
this.name
= name;
this.description
= description;
this.imgBackground
= imgBackground;
this.imgIcon
= imgIcon;
this.quantity
= quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getImgBackground() {
return imgBackground;
}
public void setImgBackground(int
imgBackground) {
this.imgBackground = imgBackground;
}
public int getImgIcon() {
return imgIcon;
}
public void setImgIcon(int imgIcon) {
this.imgIcon = imgIcon;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
// Añadir cantidad
public void addQuantity(int quantity) {
if (this.quantity < LIMIT_QUANTITY)
this.quantity += quantity;
}
// Reset cantidad
public void resetQuantity() {
this.quantity = RESET_VALUE_QUANTITY;
}
}
Suppose there is an ArrayList of Fruit named listFruits.
Write necessary Java code so that when Collections.sort(listFruits) is called,
the products are sorted by descending order of quantity and if quantity matches
then by lexicographic order of their name.[BUET OOP-2018]
Public
class College {
private int eiin;
private int shift;
private int version;
private int group;
public
College(int eiin, int shift, int version, int group) {
this.eiin = eiin;
this. shift = shift;
this.version=
version;
this.group= group;}
public static void main(String[] args) {
College c1 = new College(135790,1, 1,0);
College c2 = new College(135790, 1, 1,0);
System.out.println( c1.equals( c2);
HashMap map = new HashMap();
Map.put( c1, 100);
System.out.println(m.get( c2));
}
}
Write two differences between ArryList and Vector. Write
three differences between Hashtable and Hashmap. [BUET OOP-2018]
Difference between
ArrayList and Vector
ArrayList and Vector both implements List interface and
maintains insertion order.
But there are many differences between ArrayList and Vector
classes that are given below.
ArrayList |
Vector |
1) ArrayList is not synchronized. |
Vector is synchronized. |
2) ArrayList increments 50%of current array
size if number of element exceeds from its capacity. |
Vector increments 100% means doubles
the array size if total number of element exceeds than its capacity. |
3) ArrayList is not a legacyclass, it is introduced in
JDK 1.2. |
Vector is a legacy class. |
4) ArrayList is fast because it is
non-synchronized. |
Vector is slow because it is
synchronized i.e. in multithreading environment, it will hold the other
threads in runnable or non-runnable state until current thread releases the
lock of object. |
5) ArrayList uses Iteratorinterface to
traverse the elements. |
Vector uses Enumeration interface to
traverse the elements. But it can use Iterator also. |
Example of Java ArrayList
Let's see a simple example where we are using ArrayList to
store and traverse the elements.
import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Sonoo
Michael
James
Andy
Example of Java Vector
Let's see a simple example of java Vector class that uses
Enumeration interface.
import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output:
umesh
irfan
kumar
Difference between
HashMap and Hashtable
HashMap and Hashtable both are used to store data in key
and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and
Hashtable classes that are given below.
HashMap |
Hashtable |
1) HashMap is non synchronized. It is not-thread
safe and can't be shared between many threads without proper synchronization
code. |
Hashtable is synchronized. It is thread-safe and
can be shared with many threads. |
2) HashMap allows one null key and multiple null values. |
Hashtable doesn't allow any null key or value. |
3) HashMap is a new class introduced in JDK 1.2. |
Hashtable is a legacy class. |
4) HashMap is fast. |
Hashtable is slow. |
5) We can make the HashMap as synchronized by calling this code |
Hashtable is internally synchronized and can't be
unsynchronized. |
6) HashMap is traversed by Iterator. |
Hashtable is traversed by Enumerator and Iterator. |
7) Iterator in HashMap is fail-fast. |
Enumerator in Hashtable is not fail-fast. |
8) HashMap inherits AbstractMap class. |
Hashtable inherits Dictionaryclass. |
Differences between HashMap and
HashTable in Java
HashMap and Hashtable store
key/value pairs in a hash table. When using a Hashtable or HashMap, we specify
an object that is used as a key, and the value that you want linked to that
key. The key is then hashed, and the resulting hash code is used as the
index at which the value is stored within the table.
Sample Java code.
|
Output:
-------------Hash table--------------
103 Rahul
102 Ravi
101 Vijay
-----------Hash map-----------
100 Amit
101 Vijay
102 Rahul
104 Amit
Hashmap vs Hashtable
1. HashMap is non synchronized. It is not-thread safe and can’t be shared
between many threads without proper synchronization code whereas Hashtable is
synchronized. It is thread-safe and can be shared with many threads.
2. HashMap allows one null key and multiple null values whereas Hashtable
doesn’t allow any null key or value.
3. HashMap is generally preferred over HashTable if thread synchronization is
not needed
Why HashTable doesn’t allow
null and HashMap does?
To successfully store and retrieve objects from a HashTable, the objects used
as keys must implement the hashCode method and the equals method. Since null is
not an object, it can’t implement these methods. HashMap is an advanced version
and improvement on the Hashtable. HashMap was created later.
What is the purpose of constructors and destructors?
Write three special properties of a constructor that make it distinct from
other member functions.
[BUET OOP-2018]
Constructors
Constructors are special class functions which performs
initialization of every object. The Compiler calls the Constructor whenever an
object is created. Constructors iitialize values to object members after
storage is allocated to the object.
class A
{
int x;
public:
A(); //Constructor
};
While defining a contructor you must remeber that the name
of constructor will be same as the name of the class, and contructors never
have return type.
Constructors can be defined either inside the class
definition or outside class definition using class name and scope
resolution ::
operator.
class A
{
int i;
public:
A(); //Constructor declared
};
A::A() //
Constructor definition
{
i=1;
}
Types of Constructors
Constructors are of three types :
1. Default
Constructor
2. Parametrized
Constructor
3. Copy
COnstructor
Default Constructor
Default constructor is the constructor which
doesn't take any argument. It has no parameter.
Syntax :
class_name ()
{ Constructor Definition }
Example : class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created
the constructor is called which initializes its data members.
A default constructor is so important for initialization
of object members, that even if we do not define a constructor explicitly, the
compiler will provide a default constructor implicitly.
class Cube
{
public:
int
side;
};
int main()
{
Cube c;
cout
<< c.side;
}
Output : 0
In this case, default constructor provided by
the compiler will be called which will initialize the object data members to
default value, that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter.
Using this Constructor you can provide different values to data members of
different objects, by passing the appropriate values as argument.
Example :
class Cube
{
public:
int
side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube
c1(10);
Cube
c2(20);
Cube
c3(30);
cout
<< c1.side;
cout
<< c2.side;
cout
<< c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above
case, we have initialized 3 objects with user defined values. We can have any
number of parameters in a constructor.
Copy Constructor
These are special type of Constructors which
takes an object as argument, and is used to copy values of data members of one
object into other object. We will study copy constructors in detail later.
Constructor Overloading
Just like other member functions, constructors
can also be overloaded. Infact when you have both default and parameterized
constructors defined in your class you are having Overloaded Constructors, one
with no parameter and other with parameter.
You can have any number of Constructors in a
class that differ in parameter list.
class Student
{
int rollno;
string
name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};
int main()
{
Student
A(10);
Student
B(11,"Ram");
}
In above case we have defined two constructors
with different parameters, hence overloading the constructors.
One more important thing, if you define any
constructor explicitly, then the compiler will not provide default constructor
and you will have to define it yourself.
In the above case if we write Student S; in
main(), it will lead to a compile time error, because we haven't defined
default constructor, and compiler will not provide its default constructor
because we have defined other parameterized constructors.
Destructors
Destructor is a special class function which
destroys the object as soon as the scope of object ends. The destructor is
called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for
the constructor, the class name is used for the name of destructor, with a
tilde ~ sign as prefix to it.
class A
{
public:
~A();
};
Destructors will never have any arguments.
How constructors are different from a normal
member function?
A constructor is different from normal functions
in following ways:
§ Constructor has same name as the class itself
§ Constructors don’t have return type
§ A constructor is automatically called when an
object is created.
§ If we do not specify a constructor, C++ compiler
generates a default constructor for us (expects no parameters and has an empty
body).
What is a copy constructor?
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
§ ClassName (const ClassName &old_obj);
§ Following is a simple example of copy
constructor.
#include<iostream> using namespace std; class Point { private: int x, y; public: Point(int
x1, int y1) { x = x1; y = y1; } // Copy
constructor Point(const
Point &p2) {x = p2.x; y = p2.y; } int
getX()
{ return x; } int
getY()
{ return y; } }; int main() { Point
p1(10, 15); // Normal constructor is called here Point p2 =
p1; // Copy constructor is called here // Let us
access values assigned by constructors cout
<< "p1.x = " << p1.getX() << ", p1.y =
" << p1.getY(); cout
<< "\np2.x = " << p2.getX() << ", p2.y =
" << p2.getY(); return 0; } |
Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
When is copy constructor
called?
In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.
When is user defined copy constructor needed?
If we don’t define our own copy constructor, the C++ compiler creates a default
copy constructor for each class which does a member wise copy between objects.
The compiler created copy constructor works fine in general. We need to define
our own copy constructor only if an object has pointers or any run time
allocation of resource like file handle, a network connection..etc.
What
will be the output of the following code segment? [BUET-2018]
#include<iostream>
#include<stdio.h>
using namespace std;
class Animal
{
int age;
public:
Animal()
{cout<<"Constructing\n";
age = 0; }
~Animal()
{ cout<<
"Destructing\n"; }
};
Animal process(Animal a)
{
cout<<"In process\n";
Animal b;
b=a;
return b;
}
int main() {
cout<<"First line\n";
Animal a;
cout<<"Second line\n";
Animal b =a;
cout<<"Third line\n";
Animal c= process(b);
cout<<"Return line\n";
return 0;
}
Output:-
First line
Constructing
Second line
Third line
In process
Constructing
Destructing
Return line
Destructing
Destructing
Destructing
Briefly explain the visibility of private, protected, and
public members of a class in a derived class when the base class is inherited
as private, protected, and public by the derived class. [BUET Academic OOP-2018]
You can declare a derived class from a base class with different
access control, i.e., public inheritance, protected inheritance or private
inheritance.
#include <iostream>
using namespace std;
class base
{
};
class derived :
access_specifier base
{
};
Note: Either public, protected or private keyword
is used in place of access_specifier term used in the
above code.
Example of public,
protected and private inheritance in C++
class base
{
public:
int x;
protected:
int y;
private:
int z;
};
class publicDerived:
public base
{
// x is public
// y is protected
// z is not
accessible from publicDerived
};
class protectedDerived:
protected base
{
// x is protected
// y is protected
// z is not
accessible from protectedDerived
};
class privateDerived:
private base
{
// x is private
// y is private
// z is not
accessible from privateDerived
}
In the above example, we observe the following things:
·
base
has
three member variables: x, y and z which are public
, protected
and private
member respectively.
·
publicDerived
inherits
variables x and y as
public and protected. z is not inherited as it
is a private member variable of base.
·
protectedDerived
inherits
variables x and y.
Both variables become protected. z is not
inherited
If we derive a class derivedFromProtectedDerived
from
protectedDerived, variables x and y are also inherited to the derived class.
·
privateDerived
inherits
variables x and y.
Both variables become private. z is not
inherited
If we derive a class derivedFromPrivateDerived
from
privateDerived, variables x and y are not inherited because they are private
variables of privateDerived.
Implement a Queue class by inheriting from the List class. Your queue class
should override the three functions as follows: [BUET Academic OOP-2018]
class ListItem
{
int item;
ListItem * next;
public:
ListItem(int arg){ item = arg; next = NULL; }
int getItem(){ return
item;}
void setNext(ListItem * n){ next = n; }
ListItem *getNext() { return next; }
};
class List
{
private:
ListItem * head;
ListItem * tail;
public:
List() {head =NULL; tail = NULL; }
virtual void store(int item)=0;
virtual int
retrieve()=0;
virtual void
print()=0;
};
(i) store - override this
to add a new item at the end of the queue
(ii) retieve - override this to remove and return the value from the beginning
of the queue
(iii) print - displays the queue items as a comma separated list at the stdout
How does the copy
constructor differ from the assignment operator (=)? [BUET Academic OOP-2018]
Copy constructor and assignment operator, are the two
ways to initialize one object using another object. The fundamental difference
between the copy constructor and assignment operator is that the copy
constructor allocates separate memory to both the objects, i.e.
the newly created target object and the source object.The assignment
operator allocates same memory location to the newly created
target object as well as source object.
Key Differences Between Copy Constructor and Assignment
Operator
1.
A copy constructor is
an overloaded contructor where as an assignment operator is a bitwise operator.
2.
Using copy constructor
you can initialize a new object with an already existing object. On the other
hand, an assignment operator copies one object to the other object, both of
which are already in existance.
3.
A copy construcor is
initialized whenever a new object is initialized with an already existing
object, when an object is passed to a function as a non refrence parameter, or
when an object is returned from a function. On the other hand, an assignment
operator is invoked only when an object is being assigned to another object.
4.
When an object is
being initialized using copy constructor, the initializing object and the
initialized object shares the different memory location. On the other hand,
when an object is being initialized using an assignment operator then the
initialized and initializing objects shares the same memory location.
5.
If you do not
explicitly define a copy constructor then the compiler provides one. On the
other hand, if you do not overload an assigment operator then a bitwise copy
operation is performed.
Copy constructor vs assignment operator in C++
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
Test()
{}
Test(const
Test &t)
{
cout<<"Copy
constructor called "<<endl;
}
Test&
operator = (const Test &t)
{
cout<<"Assignment
operator called "<<endl;
}
};
int main()
{
Test t1, t2;
t2 = t1;
Test t3 =
t1;
getchar();
return 0;
}
Output:
Assignment operator
called
Copy constructor
called
Copy
constructor is called when a new object is created from an existing object, as
a copy of the existing object (see this G-Fact). And assignment operator is called when an already
initialized object is assigned a new value from another existing object.
|
What is an
in-line function? What are the advantages and disadvantages of using in- line
functions? [BUET OOP -2018]
Inline
function is the optimization technique used by the compilers. One can simply
prepend inline keyword to function prototype to make a function inline. Inline
function instruct compiler to insert complete body of the function wherever
that function got used in code.
Remember, inlining is only a request to the
compiler, not a command. Compiler can ignore the request for inlining. Compiler
may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement
doesn’t exist in function body.
5) If a function contains switch or goto statement.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function
is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context
specific optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows of calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because
inline can yield less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers,
After in-lining function if variables number which are going to use register
increases than they may create overhead on register variable resource
utilization. This means that when inline function body is substituted at the
point of function call, total number of variables used by the function also
gets inserted. So the number of register going to be used for the variables
will also get increased. So if after function inlining variable numbers
increase drastically then it would surely cause an overhead on register
utilization.
2) If you use too many inline functions then the
size of the binary executable file will be large, because of the duplication of
same code.
3) Too much inlining can also reduce your
instruction cache hit rate, thus reducing the speed of instruction fetch from
that of cache memory to that of primary memory.
4) Inline function may increase compile time
overhead if someone changes the code inside the inline function then all the
calling location has to be recompiled because compiler would require to replace
all the code once again to reflect the changes, otherwise it will continue with
old functionality.
5) Inline functions may not be useful for many
embedded systems. Because in embedded systems code size is more important than
speed.
6) Inline functions might cause thrashing
because inlining might increase size of the binary executable file. Thrashing
in memory causes performance of computer to degrade.
The following program demonstrates the use of
use of inline function.
#include <iostream> using namespace std; inline int cube(int s) { return
s*s*s; } int main() { cout
<< "The cube of 3 is: " << cube(3) <<
"\n"; return 0; } //Output: The cube of 3 is: 27 |
Suppose class A has some virtual functions and class B
publicly inherits from A. What happens if class B does not implement some of
the virtual functions of class A? Does the situation remain the same if the
virtual functions in class A were pure virtual functions? What happens when we
try to instantiate an object of class A in the second scenario mentioned
above?[BUET OOP-2018]
#include<iostream>
#include<stdio.h>
using namespace std;
class A
{
int x;
public:
void virtual f()=0;
void virtual print()=0;
};
class
B: public A
{
public:
void print()
{
cout<<"Hello world";
}
void virtual f()
{
cout<<"This is another function";
}
};
int
main()
{
B o;
o.print();
o.f();
return 0;
}
What will be
the output of the following code segment [BUET OOP-2018]
#include<iostream>
#include<stdio.h>
using namespace std;
int &f();
int x;
int
main()
{
f() = 10;
int a=10;
int b=20;
int& ref = a;
ref= b;
cout<< a <<" "
<<b <<" "<< ref<<" "<< x;
return 0;
}
int& f(){ return x;}
output:-
20 20 20 10
Explain what is wrong with the following
code segment? Rewrite the code to solve the problem. What will be the output of
the code once you fix it? [BUET OOP -2018]
#include<iostream>
#include<stdio.h>
using namespace std;
class A
{
int
x;
public:
void setX(int i) {x = i;}
void print() { cout<< x; }
};
class B: public A
{
public:
B() { setX(10); }//do not change the parameter
value while fixing the code
};
class C: public A
{
public:
C() { setX(20); }//donot change the
parameter value while fixing the code
};
class D: public B, public C {
};
int
main()
{
D d;
d.print(); // There
is error because ambiguous is occur here
for multiple inheritance get confused is it B’s member or C`s member.
That is why have to define specify.
return 0;
}
Solution:
int main()
{
D d;
// There is error because ambiguous is occur here for multiple inheritance get confused is it
B’s member or C`s member. That is why have to define specify.
d.B::print(); // or
d.C::print();// or both
return 0;
}
Output: 10 // if d.B::print()
Output: 20 // if d.C:: print()
Output: 10 20 // if d.B::print() and d.C::print() both keep
A class
"Date" contains three private variable "day",
"month" and "year". The users enter the date in Bangladeshi
form, e.g., "23/12/2016" but the. output of the program display data
in Chinese form, e.g., "2016/12/23". [BUET OOP -2017]
(i) Define the class along with the constructor;
(ii) Write down an extractor function that has the following prompt: Enter a date in
Bangladeshi form:
(iii) Write down an inserter function generating the following output: Date (Chinese
form) is 2016/12/23.
Solution:-
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
class Date
{
int
day,month,year;
public:
char str[20];
Date()
{
day=0;
month=0;
year=0;
}
void extractor()
{
cout<<"Enter a date in Bangladeshi form:";
gets(str);
}
void inserter()
{
int d=0,l;
l=strlen(str);
for(int
i=0;i<l;i++)
{
if(d!=3)
{
if(str[i]!='/'&& d==0)
day=day*10+((str[i]-48)%10);
if(str[i]=='/')
d++;
if(str[i]!='/'&& d==1)
month=month*10+str[i]-48;
if(str[i]!='/'&& d==2)
year=year*10+str[i]-48;
}
}
cout<<endl<<"Date (Chinese form) is
"<<year<<"/"<<month<<"/"<<day;
}
};
int main()
{
Date obj;
obj.extractor();
obj.inserter();
return 0;
}
Create a manipulator named "my
style" that will print a number in right justified form within a field width of 10, using a precision
of five decimal places. An integer is displayed in hexadecimal format and displays
a + sign when positive values are displayed. Create a program that prints 2 to
100 and the corresponding natural log in a table using the manipulator. [BUET OOP
-2017]
Ans:
#include
<iostream>
#include <iomanip>
#include <math.h>
using namespace std;
ostream &
mystyle(ostream & ostr)
{
cout << setw(10);
cout<<fixed;
cout << setprecision(5);
cout << right;
cout << hex;
cout << showpos;
return ostr;
}
int main()
{
for(int i=2; i<=100; i++)
{
cout<<mystyle<<i <<
" " <<log(i) << endl;
}
return 0;
}
n is a binary
number word where there is no cosecutive two 11. Write a program to find
this
Ans:
n = n & (n << 1);
if (n == 0) {
System.out.println("No
Consecutive 1's");
}else{
System.out.println("Consecutive 1's");
}
Overloadable/Non-overloadableOperators
Following
is the list of operators which can be overloaded −
+ |
- |
* |
/ |
% |
^ |
& |
| |
~ |
! |
, |
= |
< |
> |
<= |
>= |
++ |
-- |
<< |
>> |
== |
!= |
&& |
|| |
+= |
-= |
/= |
%= |
^= |
&= |
|= |
*= |
<<= |
>>= |
[] |
() |
-> |
->* |
new |
new [] |
delete |
delete [] |
Following
is the list of operators, which can not be overloaded −
:: |
.* |
. |
?: |
Consider the following class
declaration:
class Coord{
intx, y;
char *pointname;
public:
…………………
}
Create necessary constructors to support
the following two declarations in the
main function:
Coord ob1, ob2, ob3;
Coord ob4(0, 0; "origin");[BUET OOP-2017]
Solution:
#include <iostream>
using namespace std;
class Coord{
int x, y;
char *pointname;
public:
Coord()
{
x=0;
y=0;
pointname= "origin";
cout<<"x="<<x<<"
y="<<y<<" pointname= "<<pointname;
}
Coord(int X, int Y, char *point)
{
x=X;
y=Y;
pointname=point;
cout<<endl;
cout<<"x="<<x<<"
y="<<y<<" pointname= "<<pointname;
}
};
int main()
{
Coord obj;
Coord
obj1(0,0,"origin");
}
Why does copy constructor work for
initialization, but not for assignment? Explain. Create a copy constructor
required for the above class declaration.Create necessary methods for
supporting following statements in the main function [BUET OOP-2017]
ob1=ob2+ob3+ob4;
Ob1=100+ob2;
Int value=100+ob4;
Solution for ob1=ob2+ob3+ob4;
#include<iostream>
using
namespace std;
class
NUM
{
private:
int n;
public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
void
dispNum(void)
{
cout << "Number is:
" << n;
}
//add two objects - Binary Plus(+)
Operator Overloading
NUM operator +(NUM &obj)
{
NUM x; //create another object
x.n=this->n + obj.n;
return
(x); //return object
}
};
int
main()
{
NUM ob1,ob2,ob3,ob4;
ob2.getNum(10);
ob3.getNum(20);
ob4.getNum(20);
//add two objects
ob1=ob2+ob3+ob4;
ob1.dispNum();
// ob1 = 100 + ob2;
// int value = 100 + ob4;
cout << endl;
return
0;
}
How can u code
++ob1 and ob1++ differently ? [BUET OOP 2017]
#include
<iostream>
using
namespace std;
class
Test
{
private:
int count;
public:
Test(): count(5){}
void operator ++()
{
count = count+1;
}
void Display() {
cout<<"Count: "<<count; }
};
int
main()
{
Test t;
++t;
// this calls "function void operator ++()" function
return
0;
}
Postfix increment operator
#include <iostream>
using
namespace std;
class
Check
{
private:
int i;
public:
Check(): i(0) { }
Check operator ++ ()
{
Check temp;
temp.i = ++i;
return
temp;
}
Check operator ++ (int) // Notice int inside barcket which
indicates postfix increment.
{
Check temp;
temp.i = i++;
return temp;
}
void Display()
{ cout << "i = "<< i
<<endl; }
};
int
main()
{
Check obj, obj1;
obj.Display();
obj1.Display();
obj1 = ++obj; // Operator function is called, only then
value of obj is assigned to obj1
obj.Display();
obj1.Display();
obj1 = obj++; // Assigns value of obj to
obj1, only then operator function is called.
obj.Display();
obj1.Display();
return 0;
}
Explain
different types of casting used in C++ with examples. [BUET Academic OOP 2017]
Type casting
Converting an expression of a given type into
another type is known as type-casting.
We have already seen some ways to type cast:
Implicit conversions do not require any
operator. They are automatically performed when a value is copied to a
compatible type. For example:
short a=2000; int b; b=a; |
explicit conversion
C++ is a strong-typed language. Many
conversions, specially those that imply a different interpretation of the
value, require an explicit conversion. We have already seen two notations for
explicit type conversion: functional and c-like casting:
short a=2000; int b; b = (int) a; // c-like cast notation b = int (a); // functional notation |
dynamic_cast
dynamic_cast can be used only
with pointers and references to objects. Its purpose is to ensure that the
result of the type conversion is a valid complete object of the requested
class.
Therefore, dynamic_cast is always successful when we cast a class to
one of its base classes:
class CBase { }; class CDerived: public CBase { }; CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast<CBase*>(&d);
// ok: derived-to-base pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived |
static_cast
static_cast can perform
conversions between pointers to related classes, not only from the derived
class to its base, but also from a base class to its derived. This ensures that
at least the classes are compatible if the proper object is converted, but no
safety check is performed during runtime to check if the object being converted
is in fact a full object of the destination type.
class CBase {}; class CDerived: public CBase {}; CBase * a = new CBase; CDerived * b = static_cast<CDerived*>(a); |
Why is RTTI a necessary feature of C++? [BUET OOP 2017]
RTTI (Run-time type Information) in
C++
In C++, RTTI (Run-time type
information) is a mechanism that exposes information about an object’s data
type at runtime and is available only for the classes which have at least one
virtual function. It allows the type of an object to be determined during
program execution
For example, dynamic_cast uses RTTI and following program fails with error
“cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type
is not polymorphic) ” because there is no virtual function in the base class B.
|
Adding
a virtual function to the base class B makes it working.
#include<iostream> using namespace std; class B { virtual void fun() {} }; class D: public B { }; int main() { B *b = new
D; D *d =
dynamic_cast<D*>(b); if(d !=
NULL) cout
<< "works"; else cout
<< "cannot cast B* to D*"; getchar();
return 0; } |
Why is RTTI necessary?
The
question whether RTTI is necessary is
however an open one. Story has it that Bjarne Stroustrup purposefully excluded
this feature from the original C++ specification, by fear that it would be
misused.
There are indeed opportunities to overuse/misuse
reflection features, and this may have been even more of a factor when C++ was
initially introduced because there wasn't such a OOP culture in the mainstream
programmer community.
This said, with a more OOP savvy community, with
the effective demonstration of all the good things reflection can do (eg. with
languages such as Java or C#) and with the fancy design patterns in use
nowadays, I strongly believe that RTTI and reflection features at large are
very important even if sometimes misused.
What are the differences between virtual
function and pure virtual function? If a class declaration contains a pure
virtual f4nction, what is that class called and what restrictions apply to its
usage? [BUET OOP 2017]
Virtual
functions:
1) It has its definition in base class.
2) Virtual Function is declared with keyword 'virtual'
at the declaration.
Ex : virtual return_type function_name(function arguments);
3) All derived classes may or may not override, virtual
function
4) These are hierarchical in nature so it does not affect
if any derived class does not inherit it.
5) No concept of abstract classes.
Pure Virtual
functions:
1) It has no definition in base class
2) Pure Virtual Function is declared as
Ex : virtual return_type function_name(function arguments) = 0;
3) All derived classes must override,pure virtual
function.
4) Gives compilation error if derived classes are not
inherited.
5) If class is pure virtual function, then class is
declared as abstract class
Virtual functions help in run-time polymorphism.
class A{
public:
virtualvoidshow(){
cout<<
"hello from base";
}
};
class B:
public A{
public:
voidshow(){
cout<<
"hello from child";
}
};
intmain(){
A *ptr a1;
ptr=a1;
B b1;
ptr->show();
//hello from base
ptr=b1;
ptr->show();
//hello from child
}
Pure virtual function helps to implement abstract classes
in C++.
class A{
public:
virtualvoidshow()=
0;
};
class B:
public A{
public:
voidshow(){
cout<<
"hello";
}
};
intmain(){
B b1;
b1.show();
//hello
}
Difference between virtual function and pure virtual
function
The virtual function and pure virtual function both are the concepts of run time polymorphism. Polymorphism is supported by both the languages C++ and Java. In Java, the term “overriding” is used instead of ‘virtual function’, as the virtual function is the term of C++. The main difference between ‘virtual function’ and ‘pure virtual function’ is that ‘virtual function’ has its definition in the base class and also the inheriting derived classes redefine it. The pure virtual function has no definition in the base class, and all the inheriting derived classes has to redefine it.
Virtual function |
Pure Virtual Function |
'Virtual function'
has their definition in the base class. |
'Pure Virtual
Function' has no definition in the base class. |
virtual funct_name(parameter_list)
{. . . . .}; |
virtual
funct_name(parameter_list)=0; |
All derived classes
may or may not override the virtual function of the base class. |
All derived classes
must override the virtual function of the base class. |
Virtual functions
are hierarchical in nature; it does not affect compilation if any derived
classes do not override the virtual function of the base class. |
If all derived
classes fail to override the virtual function of the base class, the
compilation error will occur. |
No abstract class
concept. |
If a class contains
at least one pure virtual function, then it is declared abstract. |
Definition of Virtual Function
The
virtual function is the member function of the base class, and it is redefined
by the derived classes which inherit’s the base class. It is not necessary that
all the inheriting derived classes must redefine the virtual function, it is
only redefined by those derived classes which may require its
functioning. A virtual function is created by the declaring the function
in the base class preceded with the keyword ‘virtual’.
You can declare a derived class from a base class with different access
control, i.e., public inheritance, protected inheritance or private
inheritance.
#include
<iostream>
using
namespace std;
class base
{
};
Declaration
:
class base{
public :
virtual
type funt_name( parameter-list)
{
}
};
The
inheriting derived classes can redefine the virtual function without any
‘virtual’ keyword. Derived classes redefine the virtual function to accomplish
its task. As the virtual function is redefined in derived classes, we have
multiple forms of the same function, now, which version of the function is
being called, depends on the what kind of object is referred to invoke that
function.
In
multilevel inheritance, where a derived class that has inherited the virtual
function from its base class, when itself is used as base class for another
derived class, the virtual function still can be overridden. So, when a virtual
function is inherited its virtual nature is also inherited.
Virtual
functions are also hierarchical in nature .i.e. if a derived class do not
override/redefine the virtual function inherited from the base class and when
derived class’s object invokes that virtual function, then the virtual function
defined by the base class is invoked.
Definition of Pure Virtual Function
As
seen above if derived class do not override the virtual function then the
virtual function defined by the base class is used. But, what if the base class
itself doesn’t define the virtual function. Many times, the base class has no
definition for the virtual function, or sometimes you want that all derived
classes must override the virtual function.
To
handle these above two situations, C++ supports the concept of “Pure Virtual
Function”. A ‘pure virtual function’ is declared in base class but do not have
its definition in the base class. The pure virtual function is declared as
follows.
virtual
type funct_name(parameter_list)=0;
Key Differences Between
Virtual Function and Pure Virtual Function
1.
Virtual functions are definitely defined in the base class and
redefined (override) in the derived class. On the other hand, pure virtual
function the base class is particularly not defined in the base class
2.
Derived class if required redefine(override) the virtual
function whereas, in case of pure virtual function derived class has to
definitely redefine the pure virtual function.
3.
If the derived class fails to redefine (override) the virtual
function it can use the virtual function of the base class. On the other hand,
if derived class fails to override pure virtual function then compilation error
occurs.
4.
Base class containing the virtual function can be instantiated
i.e. its object can be created but, the base class containing pure virtual
function i.e. abstract class can not be instantiated as an abstract class is
not fully defined.
What
is virtual function? Why is a virtual function used in C++ programming? - [BUET OOP ]
Virtual Functions are used to support Runtime Polymorphism.
That is, virtual keyword
tells the compiler not to make the decision (of function binding) at
compile time, rather postpone it for runtime".
·
You
can make a function virtual by preceding the keyword virtual in its
base class declaration. For example,
·
classBase
·
{
·
virtualvoid func();
}
·
When
a Base Class has a virtual member function, any class that
inherits from the Base Class can redefine the function
with exactly the same prototype i.e. only functionality can be
redefined, not the interface of the function.
·
classDerive : publicBase
·
{
·
void func();
}
·
A
Base class pointer can be used to point to Base class object as well as a
Derived class object.
·
When
the virtual function is called by using a Base class pointer, the compiler
decides at run-time which version of the function - i.e. the Base class version
or the overridden Derived class version - is to be called. This is called Runtime
Polymorphism.
Differentiate between early binding and
late binding with appropriate examples. - [BUET OOP 2016-1]
Static Binding: The
binding which can be resolved at compile time by compiler is known as static or
early binding. Binding of all the static, private and final methods is done at
compile-time
Dynamic binding: The
binding which can be resolved at run time by compiler is known as dynamic
binding or late binding. It is also called late binding because binding happens
when program actually is running.
i) static binding
happens at compile time. dynamic binding that happens at run time.
i) In static binding
actual object is not used for binding. In dynamic binding actual object is used
for binding.
iii) Method overloading
is the best example of static binding. Method overriding is the best example of
dynamic binding.
iv) Private, static and
final methods show static binding. Other than private, static and final methods
show dynamic binding.
Description about virtual, abstract, early binding and like
these.
Virtual and abstract
Before going to virtual function, let's first have a look
at early binding and late binding.
Binding means matching the function call with the correct
function definition by the compiler. It takes place either at compile time or
at runtime.
Early Binding
In early binding, the compiler matches the function call
with the correct function definition at compile time. It is also known as Static
Binding or Compile-time Binding. By
default, the compiler goes to the function definition which has been called
during compile time. So, all the function calls you have studied till now are
due to early binding.
You have learned about function overriding in which the
base and derived classes have functions with the same name, parameters and
return type. In that case also, early binding takes place.
In function overriding, we called the function with the
objects of the classes. Now let's try to write the same example but this time
calling the functions with the pointer to the base class i.e., refernce to the
base class' object.
#include <iostream>
using namespace std;
class Animals
{
public:
void sound()
{
cout
<< "This is parent class" << endl;
}
};
class Dogs : public Animals
{
public:
void
sound()
{
cout
<< "Dogs bark" << endl;
}
};
int main()
{
Animals *a;
Dogs d;
a= &d;
a -> sound();
// early binding
return 0;
}
Now in this example, we created a pointer a to
the parent class Animals. Then by writing a= &d ,
the pointer 'a' started referring to the object d of
the class Dogs.
a -> sound(); - On calling the function sound() which
is present in both the classes by the pointer 'a', the function of the parent
class got called, even if the pointer is referring to the object of the class
Dogs.
This is due to Early Binding. We know that a is
a pointer of the parent class referring to the object of the child class. Since
early binding takes place at compile-time, therefore when the compiler saw
that a is a pointer of the parent class,
it matched the call with the 'sound()' function of the parent class without
considering which object the pointer is referring to.
Late Binding
In the case of late binding, the compiler matches the
function call with the correct function definition at runtime. It is also known
as Dynamic Binding or Runtime Binding.
In late binding, the compiler identifies the type of
object at runtime and then matches the function call with the correct function
definition.
By default, early binding takes place. So if by any means
we tell the compiler to perform late binding, then the problem in the previous
example can be solved.
This can be achieved by declaring a virtual
function.
Virtual function
Virtual Function is
a member function of the base class which is overridden in the derived class.
The compiler performs late binding on this function.
To make a function virtual, we write the keyword virtual before
the function definition.
#include
<iostream>
using
namespace std;
class Animals
{
public:
virtual void sound()
{
cout << "This is parent
class" << endl;
}
};
class Dogs : public Animals
{
public:
void sound()
{
cout << "Dogs bark"
<< endl;
}
};
int main()
{
Animals
*a;
Dogs
d;
a=
&d;
a
-> sound();
return 0;
}
Since the function sound() of the base
class is made virtual, the compiler now performs late binding for this
function. Now, the function call will be matched to the function definition at
runtime. Since the compiler now identifies pointer a as
referring to the object 'd' of the derived class Dogs, it will call the sound()
function of the class Dogs.
Compiler checks if the members of a class are private,
public or protected only at compile time and not at runtime. Since our function
is being called at runtime, so we can call any type of function, private or
public as shown in the following example.
#include <iostream>
using namespace std;
class Animals
{
public:
virtual
void sound()
{
cout
<< "This is parent class" << endl;
}
};
class Dogs : public
Animals
{
private:
virtual
void sound()
{
cout
<< "Dogs bark" << endl;
}
};
int main()
{
Animals *a;
Dogs b;
a = &b;
a->sound();
return 0;
}
Since the same function (virtual function) having
different definitions in different classes is called depending on the type of
object that calls the function, this is also a part of Polymorphism.
Pure Virtual Function
Pure virtual function is a virtual function which has no definition. Pure
virtual functions are also called abstract functions.
To create a pure virtual function, we assign a
value 0 to the function as follows.
virtual void sound() = 0;
Here sound() is a pure virtual area.
Abstract Class
An abstract class is a class
whose instances (objects) can't be made. We can only make objects of its
subclass (if they are not abstract). Abstract class is also known as abstract
base class.
An abstract class has at least one abstract function
(pure virtual function).
Let's look at an example of abstract class.
Suppose there are some employees working in a firm. The
firm hires only two types of employees- either driver or developer. Now, you
have to develop a software to store information about them.
So, here is an idea - There is no need to make objects of
employee class. We will make objects to only driver or developer. Also, both
must have some salary. So, there must be a common function to know about
salary.
This need will be best accomplished with abstract
class.
So, we can make 'Employee' an abstract class and
'Developer' and 'Driver' its subclasses.
#include <iostream>
using namespace std;
class Employee // abstract base class
{
virtual
int getSalary() = 0; // pure virtual
function
};
class Developer : public Employee
{
int salary;
public:
Developer(int s)
{
salary = s;
}
int getSalary()
{
return salary;
}
};
class Driver : public Employee
{
int salary;
public:
Driver(int t)
{
salary = t;
}
int getSalary()
{
return salary;
}
};
int main()
{
Developer d1(5000);
Driver d2(3000);
int a, b;
a = d1.getSalary();
b = d2.getSalary();
cout << "Salary of
Developer : " << a << endl;
cout << "Salary of
Driver : " << b << endl;
return 0;
}
Interface
Interface or Interface
class is a class which is the same as abstract class with a
difference that all its functions are pure virtual and it has no member
variables. Its derived classes must implement each of its virtual functions
i.e., provide definition to each of the pure virtual functions of the base
class.
class IShape
{
public:
virtual getArea() = 0;
virtual getPerimeter() = 0;
};
IShape is an interface because it contains only pure
virtual functions.
#include
<iostream>
using namespace
std;
class IShape
{
public:
virtual int getArea() = 0;
virtual int getPerimeter() = 0;
};
class Rectangle : public IShape
{
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length = l;
breadth = b;
}
int getArea()
{
return length * breadth;
}
int getPerimeter()
{
return 2*(length + breadth);
}
};
class Square : public IShape
{
int side;
public:
Square(int a)
{
side = a;
}
int getArea()
{
return side * side;
}
int getPerimeter()
{
return 4 * side;
}
};
int main()
{
Rectangle rt(7, 4);
Square s(4);
cout << "Rectangle
:" << endl;
cout << "Area : "
<< rt.getArea() << " Perimeter : " <<
rt.getPerimeter() << endl;
cout << "Square :"
<< endl;
cout << "Area : "
<< s.getArea() << " Perimeter : " <<
s.getPerimeter() << endl;
return 0;
}
So we just saw that IShape is an interface with two pure
virtual functions. These virtual functions are implemented (defined) in its
subclasses Rectangle and Square according to their requirements.
So, an interface is just an abstract class with all pure
virtual methods.
Explain
why namespace is added to C++.[BUET
OOP 2017]
Consider following C++ program.
// A program to demonstrate need
of namespace int main() { int value;
value = 0;
double
value; // Error here value =
0.0; } |
Output :
Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one
entity. So, there cannot be two variables with the same name in the same scope.
Using namespaces, we can create two variables or member functions having the
same name.
#include <iostream> using namespace std; // Variable created inside
namespace namespace first { int val =
500; } // Global variable int val = 100; int main() { // Local
variable int val =
200; // These
variables can be accessed from // outside
the namespace using the scope //
operator :: cout
<< first::val << '\n'; return 0; } |
Output:
500
5 Common reasons of using namespaces in
C++ projects
Namespaces were introduced to the C++ Standard in
1995 and usually they are defined like this:
A namespace defines a new
scope. They provide a way to avoid name collisions.
Namespaces in C++ are most often used to
avoid naming collisions. Although namespaces are used extensively in
recent C++ code, most older code does not use this facility.
1- Avoid name collisions.
As speicified before it’s the common reason, in this case
their use are just useful for the compiler, no added value for the
developer to make the code more readable and maintanable.
2- Modularize the application
Modern C++ librarires use extensively the namespaces to
modalirize their code base, and they use the “Namespace-by-feature”
approach. Namespace-by-feature uses namespaces to reflect the feature
set. It places all items related to a single feature (and only that feature)
into a single namespace. This results in namespaces with high cohesion and
high modularity, and with minimal coupling between namespaces. Items that work
closely together are placed next to each other.
Boost is the best example of grouping by feature, it
contains thousands of namespaces, each one is used to group a specific feature.
3- Anonymous namespace.
Namespace with no name avoids making global static
variable. The “anonymous” namespace you have created will only be accessible
within the file you created it in.
4- workarround of the enum issue.
“Traditional” enums in C++ export their enumerators in
the surrounding scope ,which can lead to name collisions, if two different
enums in the same have scope define enumerators with the same name.
5- Hiding details by convention
For templated libraries where the code is implemented in
header files, it’s interesting to find a way to inform the library user
that he dont need to use directly some specific types because they concern only
the implementation.
Explain
the use of try and catch in C++ with appropriate
examples.
[BUET OOP 2017]
Exception Handling in C++
One of the advantages of C++
over C is Exception Handling. C++ provides following specialized keywords for
this purpose.
try: represents a block of code
that can throw an exception.
catch: represents a block of code
that is executed when a particular exception is thrown.
throw: Used to throw an
exception. Also used to list the exceptions that a function throws, but doesn’t
handle itself.
Why Exception Handling?
Following are main
advantages of exception handling over traditional error handling.
1) Separation
of Error Handling code from Normal Code: In traditional error handling codes, there are always if
else conditions to handle errors. These conditions and the code to handle
errors get mixed up with the normal flow. This makes the code less readable and
maintainable.
2) Functions/Methods
can handle any exceptions they choose: A
function can throw many exceptions, but may choose to handle some of them. The
other exceptions which are thrown, but not caught can be handled by caller. If
the caller chooses not to catch them, then the exceptions are handled by caller
of the caller.
3) Grouping
of Error Types: In C++, both
basic types and objects can be thrown as exception. We can create a hierarchy
of exception objects, group exceptions in namespaces or classes, categorize
them according to types.
Exception Handling in C++
1) Following is a simple example to show exception handling in
C++. The output of program explains flow of execution of try/catch blocks.
#include <iostream> using namespace std; int main() { int x = -1; // Some code cout <<
"Before try \n"; try { cout
<< "Inside try \n"; if
(x < 0) {
throw x; cout
<< "After throw (Never executed) \n"; }
} catch (int x ) { cout
<< "Exception Caught \n"; } cout <<
"After catch (Will be executed) \n"; return 0; } |
Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)
2) There is a special catch block called ‘catch all’ catch(…) that
can be used to catch all types of exceptions. For example, in the following
program, an int is thrown as an exception, but there is no catch block for int,
so catch(…) block will be executed.
#include <iostream> using namespace std; int main() { try { throw
10; } catch
(char *excp) { cout
<< "Caught " << excp; } catch (...) { cout
<< "Default Exception\n"; } return 0; } |
Output:
Default Exception
3) Implicit type conversion doesn’t happen for primitive types.
For example, in the following program ‘a’ is not implicitly converted to int
#include <iostream> using namespace std; int main() { try
{ throw
'a'; } catch (int x) { cout
<< "Caught " << x; } catch
(...) { cout
<< "Default Exception\n"; } return 0; } |
Output:
Default Exception
4) If an exception is thrown and not caught anywhere, the
program terminates abnormally. For example, in the following program, a char is
thrown, but there is no catch block to catch a char.
#include <iostream> using namespace std; int main() { try
{ throw 'a'; } catch (int
x) { cout
<< "Caught "; } return 0; } |
Output:
terminate called after throwing an instance of 'char'
This application has requested the Runtime to terminate it in an
unusual way. Please contact the application's support team for
more information.
5) A derived class exception should be caught before a base
class exception. See this for more details.
When
we say "a class is final" or "a method is final" what does
that mean? Showexample codes to make a class and a method final. [BUET OOP 2017]
final keyword in java
final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a method or a class.Following are different contexts where final is used.
Final variables
When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words.
Examples :
// a final variable
final int THRESHOLD = 5;
// a blank final variable
final int THRESHOLD;
// a final static variable PI
static final double PI = 3.141592653589793;
// a blank final static variable
static final double PI;
Initializing a final variable :
We must initialize a final variable, otherwise compiler will throw compile-time
error.A final variable can only be initialized once, either via an initializer or an assignment statement. There are
three ways to initialize a final variable :
1.
You
can initialize a final variable when it is declared.This approach is the most
common. A final variable is called blank final variable,if
it is not initialized while
declaration. Below are the two ways to initialize a blank final variable.
2.
A
blank final variable can be initialized inside instance-initializer block or inside constructor.
If you have more than one constructor in your class then it must be initialized
in all of them, otherwise compile time error will be thrown.
3.
A
blank final static variable can be initialized inside static block.
Let us see above different ways of initializing a final variable through an example.
|
When to use a final variable :
The only difference between a normal variable and a final variable is that we can re-assign value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of program.
Reference final variable
:
When a final variable is a reference to an object, then this final variable is
called reference final variable. For example, a final StringBuffer variable
looks like
final StringBuffer sb;
As you know that a final variable cannot be re-assign. But in case of a reference final variable, internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity. To understand what is mean by internal state of the object, see below example :
|
Output:
Geeks
GeeksForGeeks
The non-transitivity property also applies to arrays, because arrays are objects in java. Arrays with final keyword are also called final arrays.
Note :
1.
As
discussed above, a final variable cannot be reassign, doing it will throw
compile-time error.
|
Output
Compiler
Error: cannot assign a value to final variable CAPACITY
When a final variable is created inside a method/constructor/block,
it is called local final variable, and it must initialize once where it is
created. See below program for local final variable
class Gfg { public
static void main(String args[]) { final
int i; i
= 20; System.out.println(i);
} } |
Output:
20
Note the
difference between C++ const variables and Java finalvariables.
const variables in C++ must be assigned a value when declared. For final
variables in Java, it is not necessary as we see in above examples. A final
variable can be assigned value later, but only once.
final with foreach loop : final with for-each statement is a
legal statement.
|
1. Output:
1 2 3
Explanation : Since the i variable goes out of scope with each iteration of the loop, it is actually re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables.
Final classes
When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). There are two uses of a final class :
1.
One
is definitely to prevent inheritance, as final classes cannot be extended. For
example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend
them.
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
2.
The
other use of final with classes is to create an immutable classlike the predefined String class.You can not make a class immutable
without making it final.
Final methods
When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final.We must declare methods with final keyword for which we required to follow the same implementation throughout all the derived classes. The following fragment illustrates final keyword with a method:
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// COMPILE-ERROR! Can't override.
System.out.println("Illegal!");
}
}
What is the difference between class and
structure? Why both of them are necessary in C++ programming? . [BUET OOP 2016]
C++ is an object
oriented language that mainly focuses on objects.
A) Class
1. A class in C++ can be defined as a collection
of related variables and functions encapsulated in a single structure.
2. A class in C++ is just an extension of a
structure used in the C language. It is a user defined data type. It actually
binds the data and its related functions in one unit.
3. Keyword for the declaration: Class
4. Default access specifier: Private
5. Purpose: Data abstraction and further
inheritance
6. Type: Reference
7. Usage: Generally used for large
amounts of data.
8. Its object is created on the heap
memory.
9. The member variable of class can be
initialized directly.
10. It can have all the types of constructor
and destructor.
B) Structure
1.
A structure in C++ can
be referred to as an user defined data type possessing its own operations.
2.
A structure and a
class in C language differs a lot as a structure has limited functionality and
features as compared to a class.
3.
Keyword for the
declaration: Struct
4.
Default access
specifier: Public
5.
Purpose: Generally,
grouping of data
6.
Type: Value
7.
Usage: Generally
used for smaller amounts of data.
8.
Its object is created
on the stack memory.
9.
The member variable of
structure cannot be initialized directly.
10. It can have only parameterized
constructor.
Both of them are necessary in c++
Difference between a class and a struct in C++ is
the default privacy level, and structure is a light weight operation of
programming on the other hand havy weight operation of programming. That is why
when need simple public access of data is required structure or class in that
case if structure is used would be the good choice of reason of light weight.
One the other hand if required inheritance and the feature of oop then need
class in that case there is no alternative way of class.
Explain
the difference between early binding and late binding with examples. . [BUET OOP 2016]
Static Binding: The
binding which can be resolved at compile time by compiler is known as static or
early binding. Binding of all the static, private and final methods is done at
compile-time
Dynamic binding: The
binding which can be resolved at run time by compiler is known as dynamic
binding or late binding. It is also called late binding because binding happens
when program actually is running.
i) static binding happens
at compile time. dynamic binding that happens at run time.
i) In static binding
actual object is not used for binding. In dynamic binding actual object is used
for binding.
iii) Method overloading
is the best example of static binding. Method overriding is the best example of
dynamic binding.
What
is a static member? Why are they used? Write down the rules of using static
variable and static method in a class. [BUET OOP 2017]
Static members are data members (variables) or
methods that belong to a static or a non static class itself, rather than to
objects of the class. Static members always remain the same, regardless of
where and how they are used. Because static members are associated with the
class, it is not necessary to create an instance of that class to invoke them.
Use
Static
methods in languages, such as C# and Java, can be called using the following
syntax: clsName.mthName(args), where clsName is the class name and mthName is
the static method name. Static variables can also be accessed through their
class name as follows: clsName.VarName, where VarName is the static variable
name.
Since
a static variable is associated with the class, only one copy of the variable
exists in memory. This copy is shared by all objects of that class.
Some
of the features of static members are as follows:
·
A static member has
access to all static members of its containing class, including private
members.
·
A static member can be
declared using access control modifiers.
·
A static member class
can use any other static member without qualifying its name with the name of
the containing class.
A
static member class cannot have the same name as any of its enclosing classes.
Static member classes and interfaces can be defined only within top-level
classes and other static member classes and interfaces.
Rule
of static method
Define static methods in the following
scenarios only:
1. If you are writing utility classes and they
are not supposed to be changed.
2. If the method is not using any instance
variable.
3. If any operation is not dependent on instance
creation.
4. If there is some code that can easily be
shared by all the instance methods, extract that code into a static method.
5. If you are sure that the definition of the
method will never be changed or overridden. As static methods can not be
overridden.
A static
method
is one type of method which doesn't need any object to be initialized for it to
be called. Have you noticed static
is
used in the main
function
in Java? Program execution begins from there without an object being created.
Consider the following
example:
classLanguages
{
publicstaticvoid main(String[] args)
{
display();
}
staticvoid display()
{
System.out.println("Java is my favorite programming language.");
}
}
What is functional interface in Java?
Give an example to implement the functional interface as an Anonymous Inner
class[BUET OOP 2016]
Functional interfaces have a single functionality to exhibit. For
example, a Comparable interface with a single method ‘compareTo’ is used for
comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions.
There’s an annotation
introduced- @FunctionalInterface
which
can be used for compiler level errors when the interface you have annotated is
not a valid Functional Interface.
@FunctionalInterface
interfaceMathOperation{
int operation(int a,int b);
}
Let’s try to add another
abstract method:
@FunctionalInterface
interfaceMathOperation{
int operation(int a,int b);
int operationMultiply(int a,int b);
}
Above will result into
compiler error as given below:
Unexpected@FunctionalInterface annotation
@FunctionalInterface^MathOperation is not a functional interface
multiple non-overriding abstract methods found in interfaceMathOperation
A functional interface is
valid even if the @FunctionalInterface
annotation
would be omitted. It is only for informing the compiler to enforce single
abstract method inside interface.
interfaceMathOperation{
int operation(int a,int b);
}
Conceptually, a functional
interface has exactly one abstract method. Since default methods have an
implementation, they are not abstract. Since default methods are not abstract
you’re free to add default methods to your functional
interface as many as you like.
Below is valid functional
interface:
@FunctionalInterface
interfaceMathOperation{
int operation(int a,int b);
defaultvoid doSomeMathOperation(){
//Method body
}
}
If an interface declares
an abstract method overriding one of the public methods of
java.lang.Object, that also does not count toward the
interface’s abstract method count since any implementation of the interface
will have an implementation from java.lang.Object or elsewhere.
e.g. Below is a valid
functional interface even though it declared two abstract methods. Why? Because
one of these abstract methods “equals()” which has signature equal to public
method in Object class.
@FunctionalInterface
interfaceMathOperation{
int operation(int a,int b);
@Override
publicString toString();//Overridden from Object class
@Override
publicboolean equals(Object obj);//Overridden from Object class
}
While the intended use
of Functional interfaces is for lambda expressions, method references and constructor references, they can still be used,
like any interface, with anonymous classes, implemented by classes, or created
by factory methods.
Write down some syntactic differences between C and C++
programming?[BUET OOP 2016-1]
Some syntax wise
differences between C and C++.
C++ |
C |
C++ supports
Exception Handling |
C does not support
Exception Handling |
C++ supports functions
with default arrangements. |
C does not support
functions with default arrangements |
C is a mid-level
programming language. |
C++ is a high level
language. |
C++ is a superset of
C |
When compared to
C++, C is a subset of C++. |
In C++, main()
function cannot be called through other functions. |
In C, main()
function can be called through other functions. |
:: - scope
resolution operator : - class
inheritance declaration <> - template syntax []() - lambda
syntax & - references && - r-value
rerferences |
C does`t support
those operator. |
What is meant by the term
"anonymous union"? Write down the restrictions that are applicable
for anonymous union. [BUET
OOP 2016-1]
Anonymous Union and Structure in C
In C11 standard of C, anonymous Unions
and structures were added.
Anonymous
unions/structures are also known as unnamed unions/structures as they don’t
have names. Since there is no names, direct objects(or variables) of them are
not created and we use them in nested structure or unions.
Definition
is just like that of a normal union just without a name or tag. For example,
union
{
char alpha;
int num;
};
struct
{
char alpha;
int num;
};
Since
there is no variable and no name, we can directly access members. This
accessibility works only inside the scope where the anonymous union is defined.
Following
is a complete working example of anonymous union.
#include<stdio.h>
struct
Scope
{
union
{
char
alpha;
int
num;
};
};
int main()
{
struct
Scope x;
x.num
= 65;
printf("x.alpha
= %c, x.num = %d", x.alpha, x.num);
return 0;
}
Output:
x.alpha = A, x.num = 65
#include<stdio.h>
struct Scope
{
struct
{
char
alpha;
int num;
};
};
int
main()
{
struct
Scope x;
x.num
= 65;
x.alpha
= 'B';
printf("x.alpha
= %c, x.num = %d", x.alpha, x.num);
return 0;
}
Output:
x.alpha = B, x.num = 65
Write down the inserter and the extractor
methods for the class and modify the class as necessary to work with the
inserter and the extractor. - [BUET
OOP 2016-1]
#include
<iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{
real = r; imag = i; }
friend ostream & operator <<
(ostream &out, const Complex &c);
friend istream & operator >>
(istream &in, Complex &c);
};
ostream & operator
<< (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag
<< endl;
return out;
}
istream & operator
>> (istream &in, Complex
&c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part
";
in >> c.imag;
return in;
}
Write down a generic class named "queue"
where all types of data such as integer, character, string, double and object
of any kind can be stored and queued. - [BUET OOP 2016-1]
The Queue<T> Class
In C# we use the static implementation of
queue via the Queue<T> class. Here we could indicate the type of the
elements we are going to work with, as the queue and the linked list are
generic types.
The Queue<T> – Basic Operations
Queue<T> class provides the basic
operations, specific for the data structure queue. Here are some of the most
frequently used:
-
Enqueue(T) – inserts an element at the end of the queue
-
Dequeue() – retrieves the element from the beginning of the queue and
removes it
-
Peek() – returns the element from the beginning of the queue without
removing it
-
Clear() – removes all elements from the queue
-
Contains(T) – checks if the queue contains the element
-
Count – returns the amount of elements in the queue
Queue Usage – Example
Let’s consider a simple example. Let’s create
a queue and add several elements to it. After that we are going to retrieve all
elements and print them on the console:
static void Main()
{
Queue<string> queue = new Queue<string>();
queue.Enqueue("Message One");
queue.Enqueue("Message Two");
queue.Enqueue("Message Three");
queue.Enqueue("Message Four");
while (queue.Count > 0)
{
string msg = queue.Dequeue();
Console.WriteLine(msg);
}
}
Here is how the output of the sample program
looks like:
Message One
Message Two
Message Three
Message Four
What is the different between following
two declarations in Java? [BUET
OOP 2016-1]
i)
int c[], x;
ii) int[] c, x;
Write two
different ways of creating the following array in java
0
0 0
0 0 0
0 0 0 0
0 0 0
0 0
0
Ans i): int c[],
x; c is an array and x is just a regular integer variable.
Ans ii): int[]
c, x; both c and x are arrays of type int.
Jagged Array : A
jagged array is a multi-dimensional array comprising arrays of
varying sizes as
its elements.
its also
referred to as "array of arrays".
method 1 for
creating jagged array:
int[][]
jagedArray = new int[][]{{0}, {0, 0}, {0, 0, 0,}, {0, 0, 0, 0}, {0, 0, 0}, {0,
0}, {0}};
or int[][]
jagedArray = {{0}, {0, 0}, {0, 0, 0,}, {0, 0, 0, 0}, {0, 0, 0}, {0, 0}, {0}};
method 2 for
creating jagged array:
int[][] jagedArray = new int[7][];
jagedArray[0] = new int[] {0};
jagedArray[1] = new int[] {0, 0};
jagedArray[2] = new int[] {0, 0, 0};
jagedArray[3] = new int[] {0, 0, 0, 0};
jagedArray[4] = new int[] {0, 0, 0};
jagedArray[5] = new int[] {0, 0};
jagedArray[6] = new int[]{0};
Consider the following main method: [BUET OOP 2016-1]
Write
the Java function testf in the appropriate place. You can write only one testf
function.
Solution:-
public class
TestMain {
private static int testf(String operation,
int... variableLeanthArray) {
int result = 0;
switch (operation) {
case "sum":
for
(int i : variableLeanthArray) {
result
+= i;
}
break;
case
"mult":
result
= 1;
for
(int i : variableLeanthArray) {
result
*= i;
}
break;
default:
break;
}
return result;
}
public static void main(String[]
args) {
int a = testf("sum", 1, 2, 4,
5, 6);
int b = testf("sum", 1, 3,
6);
int c = testf("mult", 1, 2,
4, 5, 6);
int d = testf("mult", 1, 3,
6);
System.out.println(a + " " + b
+ " " + " " + c + " " + d);
}
}
Write 2 (two) different ways to convert
an int value to a String. Write a Java program that takes N integers from
command line and prints the maximum and the minimum of them. [BUET OOP
2016-1]
Ans: Convert int
to String:
Method 1:
Integer.toString(intValue);
Method 1:
String.valueOf(intValue) or String.format ("%d", intValue);
Maximum and
Minimum:
public class
MaxMin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int array[];
System.out.println("Enter How Many
Number : ");
N = sc.nextInt();
array
= new int[N];
System.out.println("Enter " +
N + " Integers");
for(int i=0; i<N; i++){
array[i] = sc.nextInt();
}
int maximum, minimum;
minimum = maximum = array[0];
for(int val: array){
if(maximum<val) maximum = val;
if(minimum>val) minimum = val;
}
System.out.println("Maximum
: " + maximum + " Minimum : " + minimum);
}
}
Write a Java class named MyClass with a
variable named objectCount that keeps track the number of objects created for
MyClass.When the total number of objects is greater than 100, reinitialize
object Count to 0. [BUET OOP
2016-1]
Ans:
public class
MyClass {
private static int objectCount=0;
public MyClass() {
if(objectCount>100){ objectCount =
0;}
objectCount++;
}
public int getObjectCount(){
return objectCount;
}
}
Consider the following java code: [BUET Academic OOP 2016-1]
interface interface1{
default void f1(){}
void f2();
}
interface interface2{
void f3();
void f4();
}
abstract class class1 implements
interface1{
abstract void f5();
final void f6(){}
}
class myclass extends class1 implements
interface2{
// your code
}
Write minimum
code for myclass for successful compilation. You can't define myclass as
abstract.
Solution
interface interface1{
default void
f1(){
}
void f2();
}
interface interface2{
void f3();
void f4();
abstract class class1 implements interface1{
abstract void
f5();
final void
f6(){
}
}
public class myclassextends class1 implements
interface2{
@Override
void f5() {
}
@Override
public void
f2() {
}
@Override
public void
f3() {
}
@Override
public void
f4() {
}
}
Suppose
there are 7 methods defined as following
[BUET
OOP 2016-1]
void f1(), void
f2(), void f3(), void f4(), void f5(), void f6(), void f7()
There are also 4
interfaces named as: interface i1, i2, i3, i4
There is also a
class named as MyClass that needs to be forced to implement all the 7 methods.
But there are some constraints.
(i) Each interface can define at most 2 methods.
(ii) The class
MyClass can only implement 1 interface.
Write Java code
for MyClass to achieve this scenario.
interface i1{
void f1();
void f2();
}
interface i2 extends i1{
void f3();
void f4();
}
interface i3 extends i2{
void f5();
void f6();
}
Interface i4 extends i3{
void f7 ();
}
Public
class
MyClass implements i4{
@Override
Public
void
f1() { }
@Override
Public void f2() { }
@Override
Public void f3() { }
@Override
Public void f4() { }
@Override
Public void f5() { }
@Override
Public void f6() { }
@Override
Public
void
f7() { }
}
What are the 3 (three) uses of Java
final keyword? Consider a public class Balance declared under package'
MyPackage. Write full commands to compile and run the Balance class from
command line. [BUET
OOP 2016-1]
Uses of final
keyword:
i) When a
variable is declared with final keyword, its value can’t be modified.
ii) When a class
is declared with final keyword, it is called a final class. A final class
cannot be inherited.
iii) When a
method is declared with final keyword, it is called a final method. A final
method cannot be overridden
or i) To define
constants ii) To prevent inheritance ii) To prevent method overriding
Compile and Run
Java Program:
i) Run Command
Prompt. ii) set path=C:\Program
Files\Java\jdk1.8.0_172\bin
iii) Go to
MyPackage folder using cd command. i.e cd ../MyPackage iv) javac Balance.java v) change directory. i.e cd
.. vi) java mypackage.Balance
Consider
a MyStack class implemented with array and with the following functions: [BUET OOP 2016-1]
void push(Object o) - this method
pushes an Object o into the stack
Object
pop()
- this method pops an Object from the stack
Object top() - this method return the Object in the
top of the stack without modifying the stack
boolean isEmpty() - this method returns true if
the stack is empty, otherwise return false.
final int CAPACITY = 100 - capacity of the stack
Object [] s - the array to hold the stack
int top - the top of the stack
Here are the restrictions:
1. In MyStack,
pop () and top () cannot be performed if the stack is empty. In that case
it will trigger StackEmptyException with
the message 'Stack is Empty'.
2. In MyStack, push () cannot be performed if the stack is full. In that case it
will trigger StackFullException with the message 'Stack is full'.
Write java code for the custom exceptions
mentioned above. You also need to write the
MyStack class to trigger these exceptions
when needed.
class
StackFullException extends Exception {
public
StackFullException(String msg) {
super(msg);
}
}
class
StackEmptyException extends Exception{
public StackEmptyException(String msg) {
super(msg);
}
}
public
class
MyStack {
private
final static int CAPACITY
= 100;
private int top;
private Object[] s;
public MyStack() {
this.s = new Object[CAPACITY];
this.top = 0;
}
public void push(Object o) throws StackFullException {
if(this.top
>=CAPACITY){
thrownew
StackFullException("Stack is full");
}
s[top++] = o;
}
public Object pop()
throws StackEmptyException {
if(isEmpty()){
thrownew
StackEmptyException("Stack is Empty");
}
Object o = s[top - 1];
top--;
return o;
}
public Object top() throws StackEmptyException {
if(isEmpty()){
throw new
StackEmptyException("Stack is Empty");
}
Object o = s[top - 1];
return o;
}
public
boolean
isEmpty() {
returnthis.top == 0;
}
}
Write a program that throws and catches
exception when the value of a variable is greater than 1000. [BUET OOP-2014]
Ans: int val = 1001;
try {
if (val > 1000) {
throw new
Exception("Variable greater than 1000");
}
} catch (Exception ex) {
}
Write
an interface and a class that implements it. Write a program to show how
objects can be created using interface. [BUET OOP-2014]
Solution:
interface MyInterface {}
public class
MyClassForInterface implements MyInterface {
public static void main(String[] args) {
MyInterface myInterface = new
MyClassForInterface();
}
}
Another answer
No, you cannot create object of an interface. Though I
would love to ask, “Why on earth you need to create object of an interface?”, I
shall continue on how can you have access to interface methods.
Interface contains declaration of methods, not definition.
You can implement the interface on some class, and override the definition of
interface methods in the java class.
MyMath.java
publicinterfaceMyMath{
void add(int a,int b);
void subtract(int a,int b);
}
MyMathImpl.java
publicMyMathImpl implements MyMath{
@Override
publicvoid add(int a,int b){
System.out.println("Add Result is: "+ addPrivate(int a,int b));
}
@Override
publicvoid subtract(int a,int b){
System.out.println("Subtract Result is: "+ subtractPrivate(int a,int b));
}
privateint addPrivate(int a,int b){
return a+b;
}
privateint subtractPrivate(int a,int b){
return a-b;
}
}
After this you can expose the MyMath interface to the service so that the private methods in MyMathImpl.java can not be accessed or modified through outside.
Just create the instance of Math as follows:
MyMath mymath =newMyMathImpl();
This will allow you to call following methods:
mymath.add(5,2);//Add Result is : 7
mymath.subtract(5,2);//Subtract Result is : 3
but will not allow you to call:
mymath.addPrivate(5,2);
mymath.subtractPrivate(5,2);
What are the properties of static
variables and methods? Why the main() method is declared as static.? [BUET OOP-2014]
Static Procedure Methods
IDL static procedure methods have the syntax:
Classname.ProcedureName[, Arguments] [, KEYWORDS=Keywords]
where:
·
Classname is
a valid class name
·
ProcedureName is
the name of the static procedure method
·
Arguments are
the required or optional positional parameters
·
Keywords are
any optional keywords.
main()
method is declared as static
1.Since main method is static Java virtual Machine can
call it without creating any instance of class which contains main method.
2. Since C and C++ also has similar main method which
serves as entry point for program execution, following that convention will
only help Java.
3. If main method were not declared static than JVM has
to create instance of main Class and since constructor can be overloaded and
can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
4. Anything which is declared in class in java comes
under reference type and requires object to be created before using them but
static method and static data are loaded into separate memory inside JVM called
context which is created when a class is loaded. If main method is static than
it will be loaded in JVM context and are available to execution.
Write
down the differences between: . [BUET OOP-2014]
(i) abstract class and interface
(ii) early binding and late binding
(b) Write a method that accepts an array of Strings called SearchList and a search
String called SearchKey'as parameters. The method should determine and return
the number of occurances of SearchKey in SerchList. . [BUET OOP-2014]
(i) Difference
between abstract class and interface
Abstract class and interface both are used to achieve
abstraction where we can declare the abstract methods. Abstract class and
interface both can't be instantiated.
But there are many differences between abstract class and
interface that are given below.
Abstract class |
Interface |
1) Abstract class can have abstract and non-abstract methods. |
Interface can have only abstract methods.
Since Java 8, it can have default and static methods also. |
2) Abstract class doesn't support multiple inheritance. |
Interface supports multiple inheritance. |
3) Abstract class can have final, non-final, static and non-static
variables. |
Interface has only static and final variables. |
4) Abstract class can provide the implementation of interface. |
Interface can't provide the implementation of abstract class. |
5) The abstract keyword is used to
declare abstract class. |
The interface keyword is used to
declare interface. |
6) An abstract classcan extend another
Java class and implement multiple Java interfaces. |
An interface can
extend another Java interface only. |
7) An abstract classcan be extended
using keyword "extends". |
An interface
classcan be implemented using keyword "implements". |
8) A Javaabstract classcan have class
members like private, protected, etc. |
Members of a Java interface are public by default. |
9)Example: |
Example: |
Simply, abstract class achieves partial abstraction (0 to
100%) whereas interface achieves fully abstraction (100%).
Example of abstract class and interface in
Java
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I am a
I am b
I am c
I am d
(ii) The word binding means the
mechanism which the compiler uses to decide which method should be executed on
which call.
Early Binding -
In early binding, the compiler matches the function call
with the correct function definition at compile time. It is also known as Static
Binding or Compile-time Binding. By default, the compiler
goes to the function definition which has been called during compile time. So,
all the function calls you have studied till now are due to early binding.
Late Binding -
In the case of late binding, the compiler matches the
function call with the correct function definition at runtime. It is also known
as Dynamic Binding or Runtime Binding.
In late binding, the compiler identifies the type of
object at runtime and then matches the function call with the correct function
definition.
By default, early binding takes place. So if by any means
we tell the compiler to perform late binding, then the problem in the previous
example can be solved.
Write a code segment to create a 2-D
array of Integer class which will contain 4 rows. Each row will have 3, 1, 10
and 5 columns, respectively. [BUET OOP-2014]
Solution
int array[][] = new int[4][];
array[0] = new int[3];
array[1] = new int[1];
array[2] = new int[10];
array[3] = new int[5];
Suppose,
there are three classes A, B and C..Class C wants to inherit the properties of
both class A and B Describe two ways in
which C can inherit both A and B simultaneously. Give examples, with code [BUET OOP-2014]
Class
A {
}
Class
B {
}
Class
c:public A,B {//multiple inheritance in c++
}
Another way
Class
a{
}
Class
B:public A {
}
Class
c:public B {// multilevel inheritance
}
What is function overloading? What is
the basic difference between using an overloaded function and a generic
function? [BUET
OOP-2014]
Function Overloading
If any class have multiple functions with same names but
different parameters then they are said to be overloaded. Function overloading
allows you to use the same name for different functions, to perform, either
same or different functions in the same class
Difference
between using an overloaded function and a generic function
The short answer is that method
overloading is for passing different sets of data to a function. Generics are
for passing different types to a function.
For example, say you have a CalculatePay method
on an Employee object. You may want to have one function signature that takes
no parameters and uses the current date as the "as of" date. You may
want a second function signature that takes a date. You may want a third
function signature that takes two dates (start date and end date for the pay
period).
Using generics, you may have a CheckForDuplicate
method that takes any type of object (Employee, Customer, Lab Result, etc) and
compares it against a passed in list
How
can you call a member function of a class without creating any object of that
class? Explain. [BUET
OOP-2014]
If it’s a static method, yes. You shouldn’t create an instance
in that case, as a matter of fact. However, if it’s an instance method, you do
need to create an instance, because instance methods are allowed to access
instance properties (non-static), and you need to create a new instance with
all of these fields for it to properly run. It’s like asking what the age of a
person is without having a person, just the general concept of a person. It
wouldn’t make sense.
class
A{
String z(){
System.out.println("a");
return "sauarbh";
}
}
class
B{
A a;
A x(){
return
a;
}
}
public
class runner {
public static void main(String[] args) {
B b = new B();
A a2=b.x();
a2.z(); // Calling A class method
without creating object of it
}
}
Solution:
In
c++ member function can be access without creating object of that class if
class is friend fuction.
How
can I set up my member function so it won’t be overridden in a derived class? [vvi OOP ]
Solution: - Just
declare the function final
.
What
is a copy constructor? What are the three cases when a copy constructor is
invoked? Give examples using code. [BUET OOP-2014]
What is a copy constructor?
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
ClassName (const ClassName &old_obj);
when a copy constructor is invoked
In
C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.
Write down a function named "Compute_Volume" to compute the volume of
a 3D rectangular box with height h, width w and length 1. Then, write a new
function "New _ Compute_Volume" by changing the previous function a
little so that it can compute the volume of a rectangular box as well as that
of a cube. Remember that, a cube has only one parameter. The "New_Compute_
Volume" function should be able to. handle the following calls: [BUET OOP-2014]
* New_Compute _ Volume (30,20, I 0);
* New_Compute_ Volume (10,10,10);
* New_Compute_ Volume (10);
What
is a friend function? Can a member function of a class be a friend function of another
class? If not, mention the reasons behind it. If yes, give a code example. [BUET OOP-2014]
Friend Function Like
friend class, a friend function can be given special grant to access private
and protected members. A friend function can be:
a) A method of another class
b) A global function
Yes! A member function of a class can be a
friend function of another class.
A simple and complete
C++ program to demonstrate friend function of another class
#include <iostream> class B; class A { public: void
showB(B& ); }; class B { private: int b; public: B()
{ b = 0; } friend
void A::showB(B& x); // Friend function }; void A::showB(B &x) { // Since
show() is friend of B, it can // access
private members of B std::cout
<< "B::b = " << x.b; } int main() { A a; B x; a.showB(x);
return 0; } |
What is a virtual function? What is the
relation between run-time-polymorphism and virtual functions? [BUET OOP-2014]
A virtual function is a member function that
you expect to be redefined in derived classes. When you refer to a derived
class object using a pointer or a reference to the base class, you can call
a virtual function for that object and execute the derived
class's version of the function
Another solution:-
The main thing to note about the program is, derived class function is called using a base class pointer. The idea is, virtual functions are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime.
|
Output:
In Derived
What is the use?
Virtual functions allow us to create a list of base class pointers and call
methods of any of the derived classes without even knowing kind of derived
class object. For example, consider a employee management software for an
organization, let the code has a simple base class Employee , the class contains virtual functions like raiseSalary(), transfer(), promote(),.. etc. Different types of
employees like Manager, Engineer, ..etc may have their own implementations
of the virtual functions present in base class Employee. In our complete software, we just need to pass a list
of employees everywhere and call appropriate functions without even knowing the
type of employee. For example, we can easily raise salary of all employees by
iterating through list of employees. Every type of employee may have its own
logic in its class, we don’t need to worry because if raiseSalary() is present for a
specific employee type, only that function would be called.
class Employee { public: virtual
void raiseSalary() { /*
common raise salary code */ } virtual
void promote() { /*
common promote code */ } }; class Manager: public Employee { virtual
void raiseSalary() { /*
Manager specific raise salary code, may contain increment
of manager specific incentives*/ } virtual
void promote() { /*
Manager specific promote */ } }; void globalRaiseSalary(Employee
*emp[], int n) { for (int i
= 0; i < n; i++) emp[i]->raiseSalary();
// Polymorphic Call: Calls raiseSalary() //
according to the actual object, not //
according to the type of pointer
} |
like globalRaiseSalary(), there can be many other operations
that can be appropriately done on a list of employees without even knowing the
type of actual object.
Virtual functions are so useful that later
languages like Java keep all methods as virtual by default.
How does compiler do this magic of late resolution?
Compiler maintains two things to this magic :
vtable: A table of function pointers. It is maintained per
class.
vptr: A pointer to vtable. It is maintained per object (See this for an example).
Compiler adds additional
code at two places to maintain and use vptr.
1) Code in every constructor. This code sets
vptr of the object being created. This code sets vptr to
point to vtable of
the class.
2) Code with polymorphic function call
(e.g. bp->show() in
above code). Wherever a polymorphic call is made, compiler inserts code to
first look for vptr using
base class pointer or reference (In the above example, since pointed or
referred object is of derived type, vptr of derived class is accessed).
Once vptr is
fetched, vtable of
derived class can be accessed. Using vtable, address of derived derived class function show() is
accessed and called.
What
is wrong with the following code segment? [BUET OOP-2014]
#include<iostream>
#include<stdio.h>
using namespace std;
class base {
int x;
public:
void setx (int n) {x=n;}
void showx() {cout<< x<< "\n";}
};
class derived: private base{
int y;
public:
void sety (int n) {y=n;}
void showy() {cout<< y<< "\n";}
};
int main(){
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
return 0;
}
Output
If
derive class inherite the base class as public then output will be
10
20
Web programming
What
is Web Storage
The
HTML5's web storage feature lets you store some information locally on the
user's computer, similar to cookies but it is more secure and faster. There are two types of
web storage, which differ in scope and lifetime:
Difference between local local storage and session storage
·
Local
storage — The local storage uses the
localStorage object to store data for your entire website, permanently. That
means the stored local data will be available on the next day, the next week,
or the next year unless you remove it.
·
Session
storage — The session storage uses the
session Storage object to store data on a temporary basis, for a single window (or tab). The data disappears when
session ends i.e. when the user closes that window (or tab).
Local storage
<script
type="text/javascript">// Check if the localStorage object exists
if(localStorage){
// Store data
localStorage.setItem("first_name", "Peter"); //
Retrieve data
alert("Hi, " +
localStorage.getItem("first_name"));
}
else{
alert("Sorry, your browser do not
support local storage.");
}
</script>
Session storage
<script
type="text/javascript"> // Check if the sessionStorage object
exists
if(sessionStorage){
// Store data
sessionStorage.setItem("last_name", "Parker"); //
Retrieve data
alert("Hi, " +
localStorage.getItem("first_name") + " " +
sessionStorage.getItem("last_name"));
}
else{
alert("Sorry, your browser do not
support session storage.");
}
</script>
Garbage
Collection
Garbage collection is a process by which Java achieves better memory
management. As you know, in object oriented programming, objects communicate to
each other by passing messages. (If you are not clear about the concepts of
objects, please read the prior chapter before continuing in this session).
Garbage collection happens automatically. There is no way that you can force
garbage collection to happen. There are two methods “System.gc()” and
“Runtime.gc()” through which you can make request for garbage collation. But
calling these methods also will not force garbage collection to happen and you
cannot make sure when this garbage collection will happen.
Cross-Site Scripting (XSS)
Cross-site scripting occurs when attackers inject scripts through unsanitized
user input or other fields on a website to execute code on the site. Cross-site
scripting is used to target website visitors, rather than the website or server
itself. This often means attackers are injecting JavaScript on the website, so
that the script is executed in the visitor’s browser. Browsers are unable to
discern whether or not the script is intended to be part of the website,
resulting in malicious actions, including:
·
Session hijacking
·
Spam content being distributed to
unsuspecting visitors
·
Stealing session data
Cryptography:
Cryptography
involves creating written or generated codes that allow information to be kept
secret. Cryptography converts data into a format that is unreadable for an
unauthorized user, allowing it to be transmitted without unauthorized entities
decoding it back into a readable format, thus compromising the data.
The art of
protecting information by transforming it (encrypting it) into
an unreadable format, called ciphertext. Only those who possess a
secret key
can decipher (or decrypt) the message
into plaintext.
Encrypted messages can sometimes be broken by cryptanalysis, also called codebreaking,
although modern cryptography techniques are virtually unbreakable.
Cryptography
systems can be broadly classified into symmetric-key systems
that use a single key that both the sender and recipient have, and public-keysystems
that use two keys, a public key known to everyone and a private key that only
the recipient of messages uses.
public-key encryption
Public-key encryption is a cryptographic system that uses two keys -- a public key known to everyone and a private or secret key known only to the recipient of the message.
Example: When John wants to send a secure message to Jane, he uses Jane's public key to encrypt the message. Jane then uses her private key to decrypt it.
An important element to the public key system is that the public and private keys are related in such a way that only the public key can be used to encrypt messages and only the corresponding private key can be used to decrypt them. Moreover, it is virtually impossible to deduce the private key if you know the public key.
Public-key
cryptography,
or asymmetric cryptography, is any cryptographic system that uses pairs
of keys: public
keys which may be disseminated widely, and private keys which are known only to the owner.
In a public key encryption system, any person
can encrypt a message using the receiver's public key. That encrypted message
can only be decrypted with the receiver's private key. To be practical, the
generation of a public and private key -pair must be computationally
economical. The strength of a public key cryptography system relies on the
computational effort (work factor
in cryptography) required to find the private key from its paired public key.
Effective security only requires keeping the private key private; the public
key can be openly distributed without compromising security.
jQuery ajax() Method
Example
Change
the text of a <div> element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt",
success: function(result){
$("#div1").html(result);
}});
});
Definition and Usage
The ajax() method is used to perform an AJAX (asynchronous
HTTP) request.
All jQuery AJAX methods use the ajax() method. This method
is mostly used for requests where the other methods cannot be used.
Syntax
$.ajax({name:value, name:value, ... })
The parameters specifies one or more name/value pairs for
the AJAX request.
HTTP Request: GET vs. POST
Two commonly used methods for a request-response between a
client and server are: GET and POST.
·
GET - Requests data
from a specified resource
·
POST - Submits data
to be processed to a specified resource
GET is basically used for just getting (retrieving) some
data from the server.Note: The GET method may return cached data.
jQuery $.get() Method
The $.get() method requests data from the server with an
HTTP GET request.
Syntax:
$.get(URL,callback);
The required URL parameter specifies the URL you wish to
request.
The optional callback parameter is the name of a function
to be executed if the request succeeds.
The following example uses the $.get() method to retrieve
data from a file on the server:
Example
$("button").click(function(){
$.get("demo_test.asp", function(data,
status){
alert("Data: " +
data + "\nStatus: " + status);
});
});
The first parameter of $.get() is the URL we wish to
request ("demo_test.asp").
The second parameter is a callback function. The first
callback parameter holds the content of the page requested, and the second
callback parameter holds the status of the request.
jQuery load() Method
The jQuery load() method is a simple, but powerful AJAX
method.
The load() method loads data from a server and puts the
returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to
load.
The optional data parameter specifies a set of querystring
key/value pairs to send along with the request.
The optional callback parameter is the name of a function
to be executed after the load() method is completed.
Here is the content of our example file:
"demo_test.txt":
<h2>jQuery and AJAX is
FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
The following example loads the content of the file
"demo_test.txt" into a specific <div> element:
Example
$("#div1").load("demo_test.txt");
It is also possible to add a jQuery selector to the URL
parameter.
The following example loads the content of the element with
id="p1", inside the file "demo_test.txt", into a specific
<div> element:
Example
$("#div1").load("demo_test.txt
#p1");
The optional callback parameter specifies a callback
function to run when the load() method is completed. The callback function can
have different parameters:
·
responseTxt - contains the resulting content if the call succeeds
·
statusTxt - contains the status of the call
·
xhr - contains the XMLHttpRequest object
The following example displays an alert box after the
load() method completes. If the load() method has succeeded, it displays
"External content loaded successfully!", and if it fails it displays
an error message:
Example
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt,
statusTxt, xhr){
if(statusTxt
== "success")
alert("External
content loaded successfully!");
if(statusTxt
== "error")
alert("Error:
" + xhr.status + ": " +
xhr.statusText);
});
});
What is a closure?
A closure is an inner function that has access to the outer (enclosing)
function’s variables—scope chain. The closure has three scope chains: it has
access to its own scope (variables defined between its curly brackets), it has
access to the outer function’s variables, and it has access to the global
variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
return nameIntro + firstName + " " + lastName;
}
return
makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson
How
AJAX works? [Agrani Bank Senior Officer-IT-2018]
AJAX
communicates with the server using XMLHttpRequest object. Let's try to
understand the flow of ajax or how ajax works by the image displayed below.
As
you can see in the above example, XMLHttpRequest object plays a important role.
1.
User sends a request
from the UI and a javascript call goes to XMLHttpRequest object.
2.
HTTP Request is sent to
the server by XMLHttpRequest object.
3.
Server interacts with
the database using JSP, PHP, Servlet, ASP.net etc.
4.
Data is retrieved.
5.
Server sends XML data or
JSON data to the XMLHttpRequest callback function.
6.
HTML and CSS data is
displayed on the browser.
What is Session Hijacking ? [AME at Bangladesh
Bank- 2017]
session hijacking, sometimes also known as cookie hijacking is the
exploitation of a valid computer session—sometimes also called a session key—togain unauthorized
access to information or services in a computer system. In particular, it is
used to refer to the theft of a magic
cookie used to
authenticate a user to a remote server. It has particular relevance to web
developers, as
the HTTP cookiesused to maintain a session on many web sites can be easily
stolen by an attacker using an intermediary computer or with access to the
saved cookies on the victim's computer (see HTTP cookie theft).
How to change html attribute through html DOM? [ AP at House
Building finance corporation 2018]
Changing HTML Content
The easiest way to modify the content of an HTML element is
by using the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML
This example changes the content of a <p> element:
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New
text!";
</script>
</body>
</html>
·
The HTML document above contains a <p> element with
id="p1"
·
We use the HTML DOM to get the element with id="p1"
·
A JavaScript changes the content (innerHTML) of that element to
"New text!"
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">Old Heading</h1>
<script>
var element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
·
The HTML document above
contains an <h1> element with id="id01"
·
We use the HTML DOM to
get the element with id="id01"
·
A JavaScript changes the
content (innerHTML) of that element to "New Heading"
How
to encrypt username and password in php? [AME at Bangladesh Bank- 2017]
The
functions which are generally used to encrypt the username and password in php
are md5(), sha1() and base64_encode. These are described briefly with examples
in the below section. During Our Php course students go through several
examples, few are listed below.
ENCRYPTION
USING MD5() FUNCTION IN PHP
Syntax
: md5(string);
ENCRYPTION
USING SHA1() FUNCTION IN PHP
Syntax
: sha1(string);
It
is used in the same way as md5 function does. The examples are shown below.
Differences Between SVG and Canvas[Asst. Programmer, Sonali
Bank-2017, ICB-2018]
The HTML5 introduced the two graphical elements Canvas
and SVG for creating rich graphics on the web, but they are fundamentally different.
The following table summarizes some of the basic differences between these two
elements, which will help you to understand how to use the Canvas and SVG
elements effectively and appropriately.
SVG |
Canvas |
Vector based (composed of shapes) |
Raster based (composed of pixel) |
Multiple graphical elements, which become the part of the DOM |
Single HTML element similar to <img> in behavior |
Modified through script and CSS |
Modified through script only |
Give better performance with smaller number of objects or
larger surface, or both |
Give better performance with smaller surface or larger number
of objects, or both |
Better scalability — can be printed with high quality at any
resolution |
Poor scalability — not suitable for printing on higher
resolution |
Click fraud:
Click fraud is a type of fraud that occurs on the Internet in pay-per-click (PPC)
online advertising. In this type of advertising, the
owners of websites that post
the ads are paid an amount of money determined by how many visitors to the
sites click on the ads. Fraud occurs when a person, automated script or
computer program imitates a legitimate user of a webbrowser,
clicking on such an ad without having an actual interest in the target of the
ad's link. Click fraud is the subject of some controversy and increasing litigation due to
the advertising networks being a key beneficiary of the fraud.
How is click
fraud committed?
There are two methods of click fraud. Automated and manual.
Automated click fraud uses software to repeatedly click on your ads. Manual click fraud is done by actual people, either from within a rival company or from outside the company hired to physically click through your ads.
What can you do
to stop it?
Thankfully automatic click fraud is easy to trace, as it normally comes from the same IP address. Manual click fraud is harder to trace, especially as much manual click fraud could be construed as accidental.
Google has a click quality team, but is of course fairly clandestine about how they operate and monitor for click fraud, however Google has devised a three tiered system to deal with the threat.
·
Automatic
filter. This
filters out invalid clicks in real time. They don’t appear in your reports and
you’re not charged for them.
·
Proactive
Analysis. Google’s
team investigates anomalies and fluctuations. If anything erroneous appears to
have been carried out, your company will be credited.
·
Your own analysis. You can
raise a query yourself with Google by filling in an online form and submitting
information from your own investigation.
This third step is hugely important. The only way to have complete confidence in steering your costs away from the threat of click fraud, is to monitor the situation yourself, don't just rely on Google or any of the other search engine networks you advertise on to police your traffic.
What is difference between == and === in javascript?
[duplicate]
===, or 'strict comparison' means is
the same type and equal
== simply means equal
JavaScript has both strict and
type-converting equality comparison. For strict equality the objects being
compared must have the same type and:
·
Two strings are strictly equal when
they have the same sequence of characters, same length, and same characters in
corresponding positions.
·
Two numbers are strictly equal when
they are numerically equal (have the same number value). NaN is not equal to
anything, including NaN. Positive and negative zeros are equal to one another.
·
Two Boolean operands are strictly
equal if both are true or both are false.
·
Two objects are strictly equal if
they refer to the same Object.
·
Null and Undefined types are == (but
not ===).
Own Answer: -
Operator |
Name |
Example |
Result |
== |
Equal |
$x == $y |
Returns true if $x is equal to $y |
=== |
Identical |
$x === $y |
Returns true if $x is equal to $y,
and they are of the same type |
PHP Source:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x == $y); // returns true
because values are equal
?>
</body>
</html>
Output:-bool(true)
PHP Source:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns
false because types are not equal
?>
</body>
</html>
Output:-bool(false)
What
is difference between library and Helpers?
libraries:
For using libraries need class and related to object, otherwise not possible to
use libraries. Utility classes where
object state is important (payment, validation, authentication, etc.)
helpers: For using helper no need to class and object, Directly can possible to
access helpers without using class. Collections of related functions (not
classes) that do repetitive tasks like generating html tags or form inputs...
Simple database connection
Index.php
<html>
<form action=
"connection.php" method="POST">
Name: <input type="text"
Name= "Name"><br>
Fname: <input type="text"
Name= "Fname"><br>
Result: <input type="text"
Name= "Result"><br>
<input type="submit" name
="submit" value="submit">
</form>
</html>
connection.php
<?php
mysql_connect("localhost"
,"root",'') or die ("Database not connected");
mysql_select_db("admission")
or die ("Database not found");
if (isset($_POST['submit']))
{
$Name=$_POST['Name'];
$Fname=$_POST['Fname'];
$Result=$_POST['Result'];
}
$query=
"insert into student (Name, Fname,Result) values
('$Name','$Fname','$Result')";
if (mysql_query($query))
{
echo
"Data inserted";
}
else
{
echo
"Data not inserted";
}
?>
Advance form design
<html>
<head>
<script
type="text/javascript" src="validate.js"></script>
</head>
<body>
<form action="#"
name="StudentRegistration"
onSubmit="return(validate());">
<table cellpadding="2"
width="20%" bgcolor="99FFFF" align="center"
cellspacing="2">
<tr>
<td colspan=2>
<center><font
size=4><b>Student Registration
Form</b></font></center>
</td>
</tr>
<tr>
<td>Name</td>
<td><input type=text
name=textnames id="textname" size="30"></td>
</tr>
<tr>
<td>Father Name</td>
<td><input
type="text" name="fathername" id="fathername"
size="30"></td>
</tr>
<tr>
<td>Postal Address</td>
<td><input
type="text" name="paddress" id="paddress"
size="30"></td>
</tr>
<tr>
<td>Personal Address</td>
<td><input
type="text" name="personaladdress"
id="personaladdress" size="30"></td>
</tr>
<tr>
<td>Sex</td>
<td><input
type="radio" name="sex" value="male"
size="10">Male
<input type="radio"
name="sex" value="Female"
size="10">Female</td>
</tr>
<tr>
<td>City</td>
<td><select
name="City">
<option value="-1"
selected>select..</option>
<option value="New
Delhi">NEW DELHI</option>
<option
value="Mumbai">MUMBAI</option>
<option
value="Goa">GOA</option>
<option
value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>Course</td>
<td><select
name="Course">
<option value="-1"
selected>select..</option>
<option
value="B.Tech">B.TECH</option>
<option
value="MCA">MCA</option>
<option
value="MBA">MBA</option>
<option
value="BCA">BCA</option>
</select></td>
</tr>
<tr>
<td>District</td>
<td><select
name="District">
<option value="-1"
selected>select..</option>
<option
value="Nalanda">NALANDA</option>
<option
value="UP">UP</option>
<option
value="Goa">GOA</option>
<option
value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>State</td>
<td><select
Name="State">
<option value="-1"
selected>select..</option>
<option value="New
Delhi">NEW DELHI</option>
<option
value="Mumbai">MUMBAI</option>
<option
value="Goa">GOA</option>
<option
value="Bihar">BIHAR</option>
</select></td>
</tr>
<tr>
<td>PinCode</td>
<td><input
type="text" name="pincode" id="pincode"
size="30"></td>
</tr>
<tr>
<td>EmailId</td>
<td><input
type="text" name="emailid" id="emailid"
size="30"></td>
</tr>
<tr>
<td>DOB</td>
<td><input
type="text" name="dob" id="dob"
size="30"></td>
</tr>
<tr>
<td>MobileNo</td>
<td><input
type="text" name="mobileno" id="mobileno"
size="30"></td>
</tr>
<tr>
<td><input
type="reset"></td>
<td
colspan="2"><input type="submit" value="Submit
Form" /></td>
</tr>
</table>
</form>
</body>
</html>
Source:
Tutorial point- https://www.tutorialspoint.com/
Java T point- https://www.javatpoint.com/
Geeksforgeeks- https://www.geeksforgeeks.org
Techopedia - https://www.techopedia.com/
guru99- https://www.guru99.com/
techterms - https://techterms.com/
webopedia - https://www.webopedia.com/
study - https://study.com/
wikipedia - https://en.wikipedia.org/
cprogramming - https://www.cprogramming.com/
w3schools - https://www.w3schools.com/
Electronic hub- https://www.electronicshub.org/
0 মন্তব্যসমূহ