answersLogoWhite

0

📱

Computer Programming

A category for questions about computer programming and programming languages.

10,506 Questions

Why encapsulation important for object-oriented programming?

Imagine that we both work for the same project and first you wrote the code for a class, and then I used your class in my program. Later on, you didn't like the way the class behaved, because some of its instance variables were being set (by me from my code) to values you hadn't anticipated. Their code brought out errors in your code. (Relax, I wont do that, dont worry.) Since, it is a Java program, so you should be able just to ship out a newer version of the class, which I could replace in my programs without changing any of my own code.

The above scenario highlights two of the promises or rather i should say benefits of Object Orientation (OO): flexibility and maintainability. But these benefits will not come automatically. You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability. Just because Java supports OO concepts, it cannot write code for you. Can it?? For example, imagine if you made your class with public instance variables, and those other programmers were setting the instance variables directly, as the following code demonstrates:

public class BadExample {

public int size;

public int weight;

...

}

public class AnotherBadExample {

public static void main (String [] args) {

BadExample b = new BadExample ();

b.size = -5; // Legal but bad!!

}

}

Now go back the scenario we spoke about a paragraph ago. BadExample is your class and AnotherBadExample is my code. I have modified one of your variables in a way that it helps my code logic but that totally alters the way your class works. Now you are in trouble. How are you going to change your class in such a way that no one can alter your values directly (like what i have done in my code)? Your only choice is to write a method say setSize(int newVal) inside your class and then change the access modifier of the variable size to say, private. This will ensure that you handle instances when someone is trying to set a value to the size variable that you dont want and at the same time ensure that no one can access the size variable directly and mess with your code.

But, unfortunately, by doing that, you have broken my code. If I try to compile my AnotherBadExample class, i will get errors because the size variable is no longer visible for me.

How can we address this situation now? The best way is: not write such code where public variables are available for anyone and everyone to modify.

The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much.

If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that?

• Keep instance variables protected (with an access modifier, mostly private).

• Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.

• For the methods, use the JavaBeans naming convention of set and get.

We call the access methods getters and setters although some prefer the fancier terms accessors and mutators. (Personally, I will be using the terms getters and setters) Regardless of what you want to call them, they're methods that other programmers must go through in order to access your instance variables. They look simple, and you've probably been using them forever if you have been writing java code:

public class GoodExample {

// protect the instance variable only an instance of your class can access it

private int size;

// Provide public getters and setters

public int getSize() {

return size;

}

public void setSize(int newSize) {

size = newSize;

}

}

You are now probably mumbling, what benefit is it to have methods that do nothing and just set or get values. I would rather have a public variable. If you did that go to the first paragraph under Encapsulation and re-read the whole thing. And if you did not do that but are asking me, where is the validation code that we are supposed to have in the setSize() method to ensure no one modifies it to invalid values, my friend this is just an example class. I leave you to ponder about how the implementation needs to be. Atleast you wont end up on the receiving side of unexpected shocks because of someone like me coding along with you or worse !!!

What is a macro and its advantages?

Macros are preprocessor statements which will have specific set of instructions which are repeated in source code for several times and which wil be replaced at every call made.

1. Reduce source code length

2. Prog more readable.

3. Any modification to instructions in macro reflects in every call

4. No performance drawback by macros

1. Every call will be replaced and hence internally code length will be large.

What are the various principles of encapsulation?

The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much.

If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that?

• Keep instance variables protected (with an access modifier, mostly private).

• Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.

• For the methods, use the JavaBeans naming convention of set and get.

What is next fit algorithm?

Memory is used more evenly because the search for a free partition does not always start at the beginning of the list (forcing higher use of these partitions and lower use of the partitions at the end of the list).

What is integer type array?

An array is a collection of similar data types. An integer array is nothing but a collection of integer data types.

Ex: int a[100], int arr[100][100]

There are several types. 1D array, 2D array, Multi-Dimensional array.

But array is a contiguous allocation. And array size will always be positive. It can be given in the declaration stage or we can specify it dynamically by using malloc function.

Ex: int *a;

a=(int*)malloc(sizeof(int)*HOW_MANY_NUMBERS_YOU_WANT);

How you can access data member inside the main program in c plus plus programming language?

Public, protected and private accessors only apply to code outside of the class. Instances of a class (objects) have complete and unrestricted access to all their own instance variables (data members). They also have unrestricted access to the instance members of all other instances of the same class whenever those instances are passed as arguments to a class member method. Static methods of the class have the same privilege, as do friends of the class.

So the question isn't why an object can access its own public members without using an operator or member function. Any code outside of the class has that exact same right, but if an object has unrestricted access to its protected and private members, why should its public members be treated any differently?

How does C compiler work?

C is a programming language.

Compiler is used to convert our source code which is in high-level language or human understandable code into machine language. Compiled source code can be executed any where once if it is compiled .

Meaning c plus plus pointer to an array and pointer to a structure?

They both mean the same thing; an array is a type of data structure (a linear structure). A pointer variable is just a variable like any other, but one that is used to specifically store a memory address. That memory address may contain a primitive data type, an array or other data structure, an object or a function. The type of the pointer determines how the data being pointed at is to be treated. Pointers must always be initialised before they are accessed, and those that are not specifically pointing at any reference should always be zeroed or nullified with the NULL value. This ensures that any non-NULL pointer is pointing at something valid. Remember that pointer variables are no different to any other variable insofar as they occupy memory of their own, and can therefore point to other pointer variables.

What is weak semaphore and strong semaphore?

strong semaphores specify the order in which processes are removed from the queue, which guarantees avoiding starvation. Weak semaphores do not specify the order in which processes are removed from the queue.

How do you use command prompt and what does it do?

Command prompt is the new name for MS_DOS prompt or just DOS promt. Before the "point and click" icons we see on our desktop were invented by Bill Gates and the Microsoft Corperation, basic lines of text were used to navigate through your computer. If you look above at the address bar you will notice that the letters also have the character "/" in there. When used in combination with basic text titles, you can make what's called a destination string. A destination string is just like a map is to you and I. "c:/windows/system" tells the computer to start in the "C Drive" and find the "Windows" file and open it. Now the computer looks at the last entry "System" and looks for that file an opens it. This is just an idea of what happens and why. If you would like to learn more, go find a book called MS_DOS for Dummies. It's about as much fun as watching paint dry, but it's the backbone programming to most Microsoft, Unix, and Linux systems. (I know nothing about Mac's)

Advantages of spiral model?

1. Estimates (i.e. budget, schedule, etc.) become more realistic as work progresses, because important issues are discovered earlier.

2. It is more able to cope with the (nearly inevitable) changes that software development generally entails.

3. Software engineers (who can get restless with protracted design processes) can get their hands in and start working on a project earlier.

What role does computer programming play in robotics?

The computer looks up and calculates the information for the robot to use through it's system. However, this is only my opinion.

Here's one thing they do, and it's an elaboration of the above idea: Think of the thermostat in your home (assuming you live in an area where you need heat during the cold season). If everything is working, when the temperature goes down a little bit the thermostat sends a signal to the furnace to send heat. When the temperature goes up, the thermostat sends a signal to stop sending heat. This feedback function means that the thermostat is a servomechanism. Computers in robots act as servomechanisms in several ways.

To take an idea right out of the air, you might imagine that some robots would have to have a gyroscope, or other kind of balance device inside. When the balance system detects that the robot is going a little too far to the left, the system can send signals to appropriate parts of the robot's workings in order to correct the robot's posi

ANSWER: Computer on a robot can be just like any computer for any machine it respond to input and give out output according to a program or software embedded into the robot. The robot may be very complex with multiple loops of servo or a simple as running a motor one way or the other. The robot can be as smart as the program allowed it to be. Basically is a dumb machine which as smart as the program installed into it.

Why were vacuum tubes used in first generation computers?

I did't find anywhere that it was when I researched it.

Over 99% of computers built from 1940 to 1958 used vacuum tubes as their active elements for: logic, power supply, memory sense/drive, etc. circuits. Other computers at this time were electromechanical, magnetic, and a small number of experimental transistor computers were built.

From 1959 to about 1965 most computers used transistors as their active elements for: logic, power supply, memory sense/drive, etc. circuits. A small number off computers at this time were magnetic or used primitive monolithic ICs.

From 1964 on more and more computers used ICs, of progressively increasing density.

What is the step by step process of the igneous rock cycle?

In clastic (or detrital) sedimentary rock:

  1. Weathering of an existing body of rock by natural mechanical or chemical means.
  2. Erosion of the weathered particles by wind, water, ice, and gravity.
  3. Deposition of the particles after transportation.
  4. Compaction of the particles by the weight of overlying sediments.
  5. Cementation of the particles by mineral precipitation from surrounding fluids.

Four step that are necessary to an a program an a completely dedicated machine?

i. Reserve Machine Time;

ii. Manually Load the program into the memory.

iii. Load the starting address and begin execution.

iv. Monitor and control execution through the use of Console.

What is the definition of orthographic projection?

ISOMETRIC drawings are drawn at 60-30 degree angles.

Orthographic projections are views of a 3D object, showing 3 faces of it. The 3 drawings are aligned so that if the page were folded, it would create part of the shape. Also called multiview projections. The 3 faces of an object consist of its plan view, front view and side view

There are 2 types of orthographic projection which are 1st angle projection and 3rd angle projection.

Built-in functions in C?

You can have #include after Stdio.h ...it has so many built in mathematical functions like CIRCULAR FUNCTIONS, ABSOLUTE VALUE and more..

Sadly, built-in functions and library functions are different things... there are no built-in functions in C (except for sizeof, which isn't an actual function).

What is the best BASIC compiler?

At the moment Visual basic 2005/8, 2005 for anything older then windows xp 2008 for xp or newer i don't know about other operating systems though...

How many base class and derived class can be created in inheritance?

As many as required. The only practical limits are those imposed by the hardware. For instance, 32-bit systems can only address a maximum of 4GB, but only 2GB is actually available to applications. On 64-bit systems there is no practical limit other than hard-drive space (for the virtual memory paging file).

Remember that every class of object requires memory to store its member variables (plus padding for alignment), which has to be multiplied up by the number of instances of those classes. Thus the more complex the hierarchy, the fewer instances you can create overall. Since alignment padding can add a substantial overhead, it's best to declare member variables from largest to smallest within each class because memory is allocated in the same order the members are declared. If a v-table is required (which it typically will be in a multi-level hierarchy) this will consume additional memory: essentially one function pointer per virtual function per override.

That said, it is difficult to imagine any hierarchy so large that you will hit a memory limitation, even on a 32-bit system, unless you happen to embed a particularly large member variable in your class, such as a hi-resolution image or video, rather than use a disk-based file stream. Aside from that the main concern is in how many instances of that hierarchy can you physically construct at one time. However, you need only look at some of the hierarchies within the Microsoft Foundation Classes to realise that your probably just scratching the surface of what is actually possible.

What is an isoscles triangle?

A triangle with two angles of the same degree and the this one at a different degree.

What type of operator is used to compare two values?

Conditional operators are used to compare two values. The result of a comparison is either true or false. Boolean data types can hold the values true or false.

Here's a list of operators.

= Equal to

> Greater than

< Less than

>= Grater than or equal to

<= Less than or equal to

<> Not equal to

Whwt is the algorithm to reverse the elements of a single linked lists without using a temporary list?

The actual code depends on whether the list is singly-linked or doubly-linked, however the algorithm is largely the same for both. Of course if the list is doubly-linked there is no need to reverse the list at all since the list can simply be traversed in reverse. However, for the sake of completeness, example code is provided for both.

The Algorithm

Set the current node to be the head node then repeatedly extract the current node's next node and insert it at the head of the list until the current node's next node is NULL.



Singly-linked Example (C++)


Assuming the list is a reference that has a head node pointer, and each node in the list has a next node pointer, a singly-linked list can be reversed as follows:

// Ensure there is a head node.
if(Node* current = list.head)

{

// Ensure the current node has a next node.

while(Node* temp= current->next )

{

// Move the next node to the head of the list.

current->next = temp->next;

temp->next = list.head;

list.head = temp;

}

}


Doubly-linked Example (C++)

In doubly-linked lists, it is assumed each node has a previous node pointer as well as a next node pointer. The algorithm is essentially the same but the node pointers obviously need to be adjusted in both directions, as follows:

// Ensure there is a head node.
if( Node* current = list.head )

{

// Ensure the current node has a next node.

while(Node* temp= current->next )

{

// Move the next node to the head of the list.

current->next = temp->next;

temp->next.prev = current;

temp->next = list.head;

list.head->prev = temp;

list.head = temp;

temp->prev = NULL;

}


// If the list also has a tail node, remember to reset it!

list.tail = current;

}

In both cases, when the while() loop finishes, the current node ends up pointing at the tail node. However, the current node never actually changes -- it always points to the same node, the original head node. As each loop progresses, the current node is demoted towards the tail, one position at a time, to eventually become the tail node. When the current node has no next node, the loop terminates and the list is completely reversed.


Repeating the reversal will naturally restore the list to its original order.


Circular Lists

The exact same algorithm can also be applied to circular lists. The only major difference is that you terminate the loop when temp points to the head of the list, rather than when it is NULL.

Should I learn C or C plus plus first if I want to learn C?

Very! C++ isn't the best language out there, it certainly has its issues, but it's very powerful. It's also fairly low-level, as far as modern languages are concerned. Python has all the power with few of the costs. If you already know how to program, you should be able to pick it up in less than two hours. Most the concepts you learned in C++ (inheritance, polymorphism, etc) still apply, too. Python has the advantage of plenty of super easy-to-use libraries for many thing (such as downloading a web page). It can't hurt to try, so give Python a spin and see if it benefits you.

see related link below