question on basic oops concepts - oop

I just want to find an answer to this question
Let A be a parent class with B,C the child classes.
Now we create objects as follows,
A o1 = new A();
B o2 = new B();
C o3 = new C();
A o4 = new B();
B o5 = new A();
C o6 = new B();
From these which will all create errors and why.. I got confused a lot because from 6 we know that it is an error because b may have some specialized variables and 7 is possible and 8 is not possible.
If i'm wrong please correct me and also,
A o7 = o4;
B 08 = o5;
Kindly suggest me the right answers and with explanations and also give me links for tutorials with this kind of puzzles.

Assuming all objects are of pointer types-
1. A *o1 = new A(); // Correct
2. B *o2 = new B(); // Correct
3. C *o3 = new C(); // Correct
4. A *o4 = new B(); // A pointer to a derived class is type-compatible with a pointer to its base class. This is up casting which acts by default.
5. B *o5 = new A(); // Wrong because the other-wise relationship of the above comment isn't true. Though there is a separate concept called Down-casting which isn't valid here.
6. C *o6 = new B(); // Wrong : C, B has no hierarchial relationships
7. A *o7 = o4; // Correct because o4, o7 are both of same type
8. B *o8 = o5; // Wrong. Since, 5 itself is wrong.
Explanation for 4 & 5:
new B() calls A's constructor followed by B's constructor. So, we have sub-objects of type A*,B*. Since, there is a sub-object of type A*, the lvalue can point to it which is also equal to of type A*. This is helpful to access base class overridden virtual methods in derived class.
new A() constructs an object of type A* and returns it's address. So, return type is of A* but the receiving type is of B*. So, they both are incompatible and is wrong.
Example: Output results
#include <iostream>
using namespace std;
class A
{
public:
A(){
cout << " \n Constructor A \n";
}
virtual ~A(){
cout << "\n Destructor A \n";
}
};
class B: public A
{
public:
B(){
cout << " \n Constructor B \n";
}
~B(){
cout << "\n Destructor B \n";
}
};
class C: public A
{
public:
C(){
cout << " \n Constructor C \n";
}
~C(){
cout << "\n Destructor C \n";
}
};
int main()
{
A* obj1 = new A;
std::cout<< "******************************" << std::endl;
A* obj2 = new B;
std::cout<< "******************************" << std::endl;
A* obj3 = new C;
std::cout<< "******************************" << std::endl;
delete obj1;
std::cout<< "******************************" << std::endl;
delete obj2;
std::cout<< "******************************" << std::endl;
delete obj3;
std::cout<< "******************************" << std::endl;
return 0;
}
Results:
Constructor A
Constructor A
Constructor B
Constructor A
Constructor C
Destructor A
Destructor B
Destructor A
Destructor C
Destructor A
Notice that the order of destruction is reverse to the order of construction.

All will work except #5 & #6, in your second set, #2 will not work simply because #5 doesn't (also because 08 is not a valid variable name).
#5 doesn't work because B may have methods that are not a part of A, so new A() doesn't return an object compatible with B.
In general, you can do:
ChildOne c1 = new ChildOne();
Parent p1 = new ChildOne();
whereas you cannot do:
ChildOne c1 = new ChildTwo();
ChildOne p1 = new Parent();

This isn't a direct answer to your question, because I think the other guys have answered your case. However, I noticed that you seem to be under the illusion that objects get type checked against memory allocation.
They don't they are checked against class definitions. Let me give you an example which I hope will bring a sense of understanding:
Say we have two classes that have been defined in the same namespace, they have identical methods and properties. The only difference is their classname. As far as the compiler and runtime are concerned, these two classes would bear no relationship whatsoever.
You would have to define another OOP way of relating them. For example, you can have both classes inherit the same parent, or have them both implement the same interface.
Using the Interface method is often preferable, since many classes which bear little relationship can implement an Interface so that other objects can interact with them via the Interface methods.
OOP is quite tricky to understand, because it's really about abstraction, and bears very little relationship to coding the metal. Once you understand what the abstractions are for and how they are used together, things get easier. Good luck.

In your question, as you mentioned,
A is the superclass,
B,C are two different subclasses of A. i.e B extends A, C extends A
Let's go step by step
Now, your assginment of references to different objects is right upto 4th step.
i.e
A o1 = new A(); //Creates a new A() object and assigns it to ref. of type A. So Correct.
B o2 = new B(); //Creates a new B() object and assigns it to ref. of type B. So Correct.
C o3 = new C(); //Creates a new C() object and assigns it to ref. of type C. So Correct.
A o4 = new B(); //Subclass object being assigned to a superclass reference. That's also correct.
Now at the 5th step,
B o5 = new A(); //Will not compile since a superclass object is assigned to a subclass reference.
//This is not allowed in Java.
Reason : It is because the superclass has no idea what features did its subclass add to itself, while inheriting. So this assignment of superclass object to subclass reference is incorrect and futile.
Now at the 6th step,
C o6 = new B(); // There isn't any hiearchical relationship between B and C.
// They are just subclass of class A. This won't compile.
Now at the 7th step,
A o7 = o4; //Correct. Because both the references i.e o4 & o7 are of same type (A).
// Hence, will compile.
Now at the 8th step,
B 08 = o5; // It is wrong because the 5th step was itself wrong.
// So it will produce a compile time error.

Related

What is 'Access specifier' in Object Oriented Programming

What is 'Access specifier' in Object oriented programming ?
I have searched for it's definition several times but not get the satisfactory answer.
Can anyone please explain it to me with realistic example ?....
Thanks in advance
What are they?
This wikipedia article pretty much sums it up. But Let's elaborate on a few main points. It starts out saying:
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.1
So an Access Specifier aka Access Modifier takes certain class, method, or variable and decides what other classes are allowed to use them. The most common Access Specifiers are Public, Protected, and Private. What these mean can vary depending on what language you are in, but I'm going to use C++ as an example since that's what the article uses.
Accessor Method | Who Can Call It
-----------------------------------------------------------------------
Private | Only the class who created it
Protected | The class who created it and derived classes that "inherit" from this class
Public | Everyone can call it
Why is this important?
A big part of OOP programming is Encapsulation. Access Specifiers allow Encapsulation. Encapsulation lets you choose and pick what classes get access to which parts of the program and a tool to help you modularize your program and separate out the functionality. Encapsulation can make debugging a lot easier. If a variable is returning an unexpected value and you know the variable is private, then you know that only the class that created it is affecting the values, so the issue is internal. Also, it stops other programmers from accidentally changing a variable that can unintentionally disrupt the whole class.
Simple Example
Looking at the example code from the article we see Struct B i added the public in there for clarity:
struct B { // default access modifier inside struct is public
public:
void set_n(int v) { n = v; }
void f() { cout << "B::f" << endl; }
protected:
int m, n; // B::m, B::n are protected
private:
int x;
};
This is what would happen if you created an inherited struct C that would try and use members from struct B
//struct C is going to inherit from struct B
struct C :: B {
public:
void set_m(int v) {m = v} // m is protected, but since C inherits from B
// it is allowed to access m.
void set_x(int v) (x = v) // Error X is a private member of B and
// therefore C can't change it.
};
This is what would happen if my main program where to try and access these members.
int main(){
//Create Struct
B structB;
C structC;
structB.set_n(0); // Good Since set_n is public
structB.f(); // Good Since f() is public
structB.m = 0; // Error because m is a protected member of Struct B
// and the main program does not "inherit" from struct B"
structB.x = 0; // Error because x is a private member of Struct B
structC.set_n() // Inheritied public function from C, Still Good
structC.set_m() // Still Good
structC.m = 0 // Error Main class can't access m because it's protected.
structC.x = 0; // Error still private.
return 0;
}
I could add another example using inheritance. Let me know if you need additional explanation.

A language that has function scoped, class life time variable

After asking this question, I just wondered is there any language that has this concept. Consider this piece of arbitrary code:
class Foo {
void bar() {
static int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 2
foo2.bar(); // prints 3
So the static i variable shared across all instances of Foo class and it's life time starts at first encounter and lasts all program long. What I wonder is, is there any language that has some_magic_keyword for defining a variable, that makes the variable function scoped and makes it life time equal to it's class life time and not sharing it along the instances of the class. So the code can be something like this:
class Foo {
void bar() {
some_magic_keyword int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 0
foo2.bar(); // prints 1
delete foo2; // the "i" variable is also deleted from memory, so no memory leaks
There is some questions about if we can implement this in some particular language but I couldn't find any asking if any language has it.
And it doesn't have to be an object oriented language, I can't think of any functional language with this concept for obvious reasons but if you can make the analogy, why not?
EDIT: If there isn't any which seems like, why not? I mean the concept is pretty straightforward. Actually when I first used a static variable in a function, I was expecting the same behaviour I'm asking here.

Method returns an object of a different class

I have noticed a situation where there is a class (say: ClassA) with variable declarations and various methods. And in another class (say: Class B), there is a method(MethodofClassB()) with the return type of the method as ClassA.
so it is like:
Class A
{
variable i,j;
public int MethodA()
{
//some operation
}
}
Class B
{
variable x,y;
public static A MethodB()
{
//some operation
return obj;
}
}
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
please help me understand this with a small example
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
Depends on what the method does, which isn't illustrated in this example. If the result of the operation is an instance of A then it stands to reason that it would return an instance of A, whatever A is.
For example, if A is a Car and B is a CarFactory then the method is likely producing a new Car. So it would return a Car that's been produced.
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
public allows it to be accessed by other objects. static means it's not associated with a particular instance of B. Both are subjective based, again, on the purpose of the method (which isn't defined in the example). Being static, it can be called as such:
var newInstance = B.MethodB();
If it wasn't static then an instance of B would be required:
var objectB = new B();
var newInstance = objectB.MethodB();
There are more and more implications here, including things like memory/resource usage and thread safety. All stemming from the purpose and business logic meaning of what B is and what MethodB does.
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
It would be an instance of A. Similar to creating an instance here:
var objectA = new A();
This method also creates (or in some way gets) an instance:
var objectA = B.MethodB();
Without knowing more about what A is, what its constructor does, and what MethodB does, these two operations are otherwise the same.
First, your code is incorrect. There is no "ClassA" class. The class name is A, so the return type should be A not ClassA.
Second, the standard Java coding standards say to start methods and variables with lower case letters. So, your example should have been:
Class A
{
A anA;
B aB;
public int methodA()
{
//some operation
}
}
Class B
{
SomeType x, y;
public static A methodB()
{
//some operation
return obj;
}
}
David's answer shortly before mine is technically correct on points 1 and 2, although he also uses your mistake of calling the A type ClassA. His code for his answer to point 3, though, is incorrect and misleading. I would change his wording to this:
`3)What would the returned objct look like. I mean if my method returned an
integer, it would return some numerical value say '123' . If a method returns
an object of a class, what would be in the returrned value`.
It would be an instance of class A. Similar to creating an instance here:
A objectA = new A();
This method also creates (or in some way gets) an instance:
A objectA = B.methodB();
Without knowing more about what class A is, what its constructor does, and what methodB does, these two operations are otherwise the same.

How to create a method of a structure in golang that is called automatically?

I have to create a something like a substitute of 2 levels of inheritance in golang, i.e.,
in a package, I have a structure(A), which is inherited(embedded as an anonymous field) by another structure(B) in another package, whose object is to be utilized by the "main" package.
Now, I've created an initializer method for the "B" (BPlease) that returns an object of B (say,B_obj). I can call this initializer(BPlease) from my "main" package at the start of the program.
One of the methods of "B" (say, HelloB()), calls a method of "A"(say,HelloA()) during execution, using "B's" object.
But what I really want is, something like a constructor for "A" that can initialize its fields (preferably when B_obj was created in package "main") before "B" calls any methods of "A".
How to achieve this?
I tried creating an initializer(APlease) for "A" as well and called it (BPlease) to get an object of "A" (A_obj). But I found this object useless as I couldn't utilize it to call "A's" method (HelloA()) inside a method of "B" (HelloB()).
It would be great if someone can tell me how to utilize this object (A_obj).
Here's some code to clarify my query:
package A
type A struct { whatever }
func (A_obj *A) HelloA(){performs some operation...} // a method of A()
func APlease() A {
return A{initialize A fields}
}
-------------------------------------------------------------------------------
package B
type B struct {
A
B fields
}
func BPlease() B {
return B{
A_obj := APlease() // useless to me.... how to utilise this?
initialize B fields}
}
func (B_obj *B) HelloB(){ // a method of B{}
call B_obj.HelloA() // valid as A is an anon field in B struct
some other operations // but A's fields are not initialized for B_obj
...}
---------------------------------------------------
package main
import "B"
import "A"
func main(){
B_obj := B.BPlease() // what I want is, calling this should initialize A's fields for B_obj as well so that when HelloB() calls B_obj.HelloA(), it utilises A's field that have been initialized.
}
I cannot pass all field-values as parameters to B_obj as there are a lot of fields, and also, some field values are generated by calling a method of the same structure.
Regardless of anyone's opinion about fighting the language to have inheritance when it doesn't: No, there are no magic methods, like "getter" or "setter" of whatever. Remotely related (magic powers) are perhaps finalizers, but they're surely not going to help in this case.
However, let me suggest to stop coding language X in Go. Just use Go. Go doesn't use "class-like" inheritance, nor a Go programmer (usually) should. Think of Go like a modernized C. There's no much C code out there relying on inheritance. (OK, I know about GObject ;-)
Some meta-remark: "First structure" and "second structure" make it very hard to understand which one is which. Labeling the different things like A, B and C is the tool which make math so powerful.
Is this your question:
You have two type A and B, B embeds A. You want to make sure B is "fully initialized" in the sense of A is also initialized.
Raw sketch:
type A struct { whatever }
type B struct {
A
more stuff
}
func APlease(params for an A) A {
return A{fields set up from params}
}
func BPlease(params forn an A and for an B) B {
return B{
A: APlease(stuff for A),
more: set from params for B,
}
}
Should do this: You can ask for a proper set up B by calling BPlease with the necessary parameters for both, the embedded A and the rest of B.
To expand on Volker's answer a bit, you should be able to call
func BPlease() B {
a_obj := A.APlease() // initialize the fields of A like normal
b_obj := B{} // create a B, whose anonymous fields are not initialized yet
b_obj.A = a_obj // PERHAPS WHAT YOU WANT: copy all a's fields to b's fields.
// if you are relying sending a_obj's address somewhere in
// APlease(), you may be out of luck.
b_obj.field_unique_to_B = "initialized"
return b_obj
}
Now that you can create B objects with fields initialized by APlease(), you can call A's methods on B's objects, and even call A's methods from within B like so:
func (B_obj *B) HelloB(){
// can't call B_obj.HelloA() like you would expect
B_obj.A.HelloA() // this works. Go "promotes" the anonymous field's methods
// and fields to B_obj
// but they don't appear in B_obj, they appear in B_obj.A
fmt.Printf("And hello from B too; %s", B_obj.field_unique_to_B)
}
I will echo Rick-777 here and suggest you stick to go's naming conventions and idioms; NewReader is much easier to read and understand than ReaderPlease.
I contrived an example that I can put on bitbucket if people want. I think it's much easier to read when you are working with real metaphors; also a disclaimer - this is not the best code, but it does some things that answer your question.
file: car/car.go
package car
import "fmt"
type BaseCar struct {
Doors int // by default, 4 doors. SportsCar will have 2 doors
Wheels int
}
func NewBaseCar() BaseCar {
return BaseCar{Wheels: 4, Doors: 4}
}
// this will be used later to show that a "subclass" can call methods from self.BaseCar
func (c *BaseCar) String() string {
return fmt.Sprintf("BaseCar: %d doors, %d wheels", c.Doors, c.Wheels)
}
// this will be promoted and not redefined
func (c *BaseCar) CountDoors() int {
return c.Doors
}
file sportscar/sportscar.go
package sportscar
// You can think of SportsCar as a subclass of BaseCar. But go does
// not have conventional inheritence, and you can paint yourself into
// a corner if you try to force square c++ structures into round go holes.
import ( "../car" ; "fmt" )
type SportsCar struct {
car.BaseCar // here is the anonymous field
isTopDown bool
}
func NewSportsCar() SportsCar {
conv := SportsCar{} // conv.Wheels == 0
conv.BaseCar = car.NewBaseCar() // now conv.Wheels == conv.Doors == 4
conv.isTopDown = false // SportsCar-only field
conv.Doors = 2 // Fewer Doors than BaseCar
return conv
}
// SportsCar only method
func (s *SportsCar) ToggleTop() {
s.isTopDown = !s.isTopDown
}
// "overloaded" string method note that to access the "base" String() method,
// you need to do so through the anonymous field: s.BaseCar.String()
func (s *SportsCar) String() string {
return fmt.Sprintf("Sports%s, topdown: %t", s.BaseCar.String(), s.isTopDown)
}
file main.go
package main
import ( "./car" ; "./sportscar" ; "fmt")
type Stringer interface { // added this complication to show
String() string // that each car calls its own String() method
}
func main() {
boring := car.NewBaseCar()
fancy := sportscar.NewSportsCar()
fmt.Printf(" %s\n", Stringer(&boring))
fmt.Printf("%s\n", Stringer(&fancy))
fancy.ToggleTop()
fmt.Printf("%s\n", Stringer(&fancy))
fmt.Println("BaseCar.CountDoors() method is callable from a SportsCar:", fancy.CountDoors())
}
There are ways to mimic inheritance in Go if this is what you are looking for, see section "Inheritance" in this blog

What is an abstract data type in object oriented programming?

What is an abstract data type in object oriented programming? I've gone through the wiki for this topic, but I am still unclear about it. Could someone clarify?
An abstract class is a generalization concept. It is a class you invent to only use as a base class for inheritance but not to instantiate objects from.
And abstract datatype (ADT) is not necessarily an OOP concept. It is an older term to describe the concepts of for example Stack and Queue in terms of their functionality, without describing the implementation.
There is a difference between an "abstract data type" and an "abstract class".
An abstract class is one that may not have definitions for all the methods it defines. You therefore cannot directly instantiate an abstract class. You have to create a subclass and then instantiate that.
An abstract data type is a model of a certain kind of data structure e.g. a Stack. A Stack has push() and pop() operations and that have well-defined behaviour.
The abstract data type (ADT) itself refers to this model, not any particular implementation in any particular programming language or paradigm. You could implement a Stack in an object-oriented language, but you could also implement it in a functional programming language.
ADTs allow discussion about the properties of Stacks, Queues etc that hold for all correct implementations of the ADT.
Well, it's all about abstraction. Abstraction is particularly useful in programming. The main advantage is ability to hide realization details. You hide it inside one modules (so-called "server modules") and provide some public interface for other modules (so-called "client modules"). And now we have three different possibilities:
Server module can supply an abstract data structure (ADS) itself.
In that case it contains ADS entity itself. The public interface consists of some procedures (and maybe some constants).
Interface of server module (stack_ads.h):
#ifndef STACK_ADS
#define STACK_ADS
const int capacity = 10;
void clear();
int size();
int pop();
void push(int value);
#endif STACK_ADS
Implementation (stack_ads.cpp):
#include "stack_ads.h"
int items[capacity];
int top = -1;
void clear()
{
top = -1;
}
int size()
{
return top + 1;
}
int pop()
{
top -= 1;
return items[top + 1];
}
void push(int value)
{
top += 1;
items[top] = value;
}
In the client module (main.cpp) we import server module and use data structure directly.
#include <iostream>
#include "stack_ads.h"
int main (int argc, char* const argv[])
{
push(1);
push(2);
push(3);
std::cout << pop() << std::endl;
std::cout << pop() << std::endl;
std::cout << pop() << std::endl;
return 0;
}
Server module can supply an abstract data type (ADT) in the form of struct/record.
In client module we can declare variables to be of that type. Because a module is free to declare more than one variable to be of the exported type, it can have more than one data structure. Each abstract data structure is variable of abstract data type.
Interface (stack_adt.h):
#ifndef STACK_ADT
#define STACK_ADT
const int capacity = 10;
typedef struct
{
int items[capacity];
int top;
} StackADT;
void clear(StackADT* stack);
int size(StackADT* stack);
int pop(StackADT* stack);
void push(StackADT* stack, int value);
#endif STACK_ADT
Implementation (stack_adt.cpp):
#include "stack_adt.h"
void clear(StackADT* stack)
{
stack->top = -1;
}
int size(StackADT* stack)
{
return stack->top + 1;
}
int pop(StackADT* stack)
{
stack->top -= 1;
return stack->items[stack->top + 1];
}
void push(StackADT* stack, int value)
{
stack->top += 1;
stack->items[stack->top] = value;
}
Client module:
#include <iostream>
#include "stack_adt.h"
int main (int argc, char* const argv[])
{
StackADT stack1;
StackADT stack2;
stack1.top = -1;
stack2.top = -1;
push(&stack1, 1);
push(&stack1, 2);
push(&stack1, 3);
std::cout << pop(&stack1) << std::endl;
std::cout << pop(&stack1) << std::endl;
std::cout << pop(&stack1) << std::endl;
push(&stack2, 10);
push(&stack2, 20);
push(&stack2, 30);
std::cout << pop(&stack2) << std::endl;
std::cout << pop(&stack2) << std::endl;
std::cout << pop(&stack2) << std::endl;
return 0;
}
Finally the server module can supply an abstract data type (ADT) in the form of class.
If our language support OOP we can describe ADT by means of classes. And once again in client module we can declare variables to be of that type. In object-oriented terminology, the type is called a class, and the variable with that type is called an object.
Server module interface (Stack.h):
#ifndef STACK
#define STACK
const int capacity = 10;
class Stack
{
public:
Stack();
void clear();
int size();
int pop();
void push(int value);
private:
int items[capacity];
int top;
};
#endif STACK
Implementation (Stack.cpp):
#include "Stack.h"
Stack::Stack()
{
this->top = -1;
}
void Stack::clear()
{
this->top = -1;
}
int Stack::size()
{
return this->top + 1;
}
int Stack::pop()
{
this->top -= 1;
return this->items[this->top + 1];
}
void Stack::push(int value)
{
this->top += 1;
this->items[this->top] = value;
}
The differences between two last options are:
Terminological mentioned above (type <-> class, variable <-> object).
In the non-class ADT, the formal parameter list of every procedure must include a variable s of type Stack. In the stack class, the specification of the data structure s is not included with the other formal parameters following the name of the procedure, but
stands alone enclosed in parentheses before the name of the procedure. Using Smalltalk terminology formal parameter before the procedure name is called the receiver.
The location of the procedures. In the non-class ADT, the procedures are located outside the Stack struct. In the class, the procedures are located within the class. In object-oriented terminology, procedures that have receivers, and are therefore contained within a class type, are called methods.
Client code:
#include <iostream>
#include "stack.h"
int main (int argc, char* const argv[])
{
Stack stack1;
Stack stack2;
stack1.push(1);
stack1.push(2);
stack1.push(3);
std::cout << stack1.pop() << std::endl;
std::cout << stack1.pop() << std::endl;
std::cout << stack1.pop() << std::endl;
stack2.push(10);
stack2.push(20);
stack2.push(30);
std::cout << stack2.pop() << std::endl;
std::cout << stack2.pop() << std::endl;
std::cout << stack2.pop() << std::endl;
return 0;
}
An Abstract Data Type (ADT) is a mathematical model of a type of data. It describes operations that can be performed on the data and the mathematical definition of those operations using equations.
For example, you can model the behaviour of a stack of numbers, perfectly abstractly using operations such as pop(), push(), top() and maybe a constant symbol representing the empty stack.
For example here are some equations that could form part of the definition of a stack of numbers:
pop(empty) = empty // silently ignores popping an empty stack
pop(push(N,S)) = S // i.e. pop removes the top element of push(N,S)
top(push(N,S)) = N // return topmost element of the stack without changing the stack
An abstract data type isn't at all the same thing as a class in an object model - although they bare some similarities.
Here are the names of the important concepts: initial algebra semantics, isomorphism, quotients, congruences
The point of an abstract data type is to understand the behaviour of a whole class of equivalent type representations using equations and some fancy mathematics that demonstrates that each implementation is "isomorphic" - i.e. that both implementations are exactly equivalent as far as the observable behaviour is concerned.
The wikipedia entry on this is pretty good: http://en.wikipedia.org/wiki/Abstract_data_type
Here are some good (but very theoretical) course notes that pin down what an ADT is http://www-compsci.swan.ac.uk/~csulrich/ftp/adt/adt.pdf
Although superficially similar to the concept of a "class" in some object-oriented programming languages, a "class" is not an ADT, but a class can be used to implement a specific ADT.
In general the ADT concept is probably more applicable to functional programming than object-oriented programming because not all object-oriented programming languages have classes and ADT-style thinking produces less effective OO designs.
Here's a paper that demonstrates the problems of thinking in terms of ADTs in an OO language: http://portal.acm.org/citation.cfm?id=74885
Basically the paper shows that the "class" that you use to implement an ADT ends up covered with lots of tiny little methods (that look like the basis of ADT equations) rather than having a few powerful, high-abstraction methods.
Definition:
Roughly speaking, Abstract Data Type (ADT) is a way of looking at a data structure: focusing on what it does and ignoring how it does its job.
Abstract data types are defined primarily by their interface: the permissible operations that can be carried out on them. The underlying mechanism used to
implement them is typically not visible to their user.
Examples:
Stack, Queue and PriorityQueue are some of the examples of the ADTs, they are more abstract than say arrays, linked lists and many other data storage structures.
For example, the underlying mechanism for a stack, can be an Array or it can be a LinkedList. The underlying mechanism for a PriorityQueue can be an Array or a special kind of tree called a Heap.
Code:
Here is a Java example of the abstract data type called PriorityQueue, implemented using the Heap:
class Heap {
private Node heapArray[];
public void insert(Node node) {...}
public Node remove() {...}
}
class PriorityQueue {
private Heap heap;
public void insert(Node node) {
heap.insert(node);
}
public Node remove() {
return heap.remove();
}
}
Here you can see that the methods for the PriorityQueue class are simply wrapped around the methods for the underlying Heap class. Similarly you can use Array instead of Heap to implement the same functionality, even though in case of Array you'll need more code to take care of operations like insert and remove. This example should make it conceptually clear that a PriorityQueue is an ADT that can be implemented in a variety of ways, using heap, arrays and so on.
Although, ADTs make more sense in object oriented programming (OOP) languages, they are not limited to only OOP languages and can also be created using non-OOP languages.
In the school they taught me that an ADT is just a group which contains a collection of data, and a set of operations that can be taken over this data. It just refers to the idea, and is not related with any ,language, implementation neither paradigm.
Updated:
so re-reading the question, and accordingly to mi definition, an abstract data type in OOP should be a class abstraction, inherited or not, because it contains data (properties, fields, etc) and operations (methods).
regards
Abstract is most fundamental and generalized concept in a programming and real life.
What is an abstract data type in object oriented programming?
ADT is a container which holds different types of objects with specifications. logical representation(i.e an interface or protocol) of the data and the operations to manipulate the component elements of the data.
Examples of ADT: List, Map, Set, Stack, Queue, Tree, Graph.
Data structures can implement one or more particular abstract data types (ADT). In java for example ArrayList, LinkedList, Stack and Vector are data structures implementation(classes) of List.
Stack examples in real life:
When a person wear bangles the last bangle worn is the first one to
be removed and the first bangle would be the last to be removed.
This follows last in first out (LIFO) principle of stack.
In a stack of plates, once can take out the plate from top or can
keep plate at the top. The plate that was placed first would be the
last to take out. This follows the LIFO principle of stack.
Batteries in the flashlight :- You cant remove the second battery
unless you remove the last in. So the battery that was put in first
would be the last one to take out. This follows the LIFO principle
of stack.
Clothes in the trunk
queue examples in real life
A queue of people at ticket-window: The person who comes first gets the ticket first. The person who is coming last is getting the tickets in last. Therefore, it follows first-in-first-out (FIFO) strategy of queue.
Vehicles on toll-tax bridge: The vehicle that comes first to the toll tax booth leaves the booth first. The vehicle that comes last leaves last. Therefore, it follows first-in-first-out (FIFO) strategy of queue.
Luggage checking machine: Luggage checking machine checks the luggage first that comes first. Therefore, it follows FIFO principle of queue.
Patients waiting outside the doctor's clinic: The patient who comes first visits the doctor first, and the patient who comes last visits the doctor last. Therefore, it follows the first-in-first-out (FIFO) strategy of queue.
The above examples collected from Source1 and Source2
Take one step back from the code:
What does abstract mean?
Abstract
The gist of it is "not real, but capturing a property of real things"
You need to know this for OOP because you will be designing object universes, which requires you to think about how those objects are related.
Abstraction allows you to group some of those objects, thus organizing
1) Your thinking process
2) Your code
I had the same problem until last week.
An abstract class is something that is common or something in general. You can use that class to mould it and extend it in anyway you like.
I can give you a practical example here
Take a class called animal. And it contains functions like eat, sound, move which is general that all animals do. You can extend that class to get specific like cats, dogs etc.
eg.
abstract class animal {
abstract protected function eat();
abstract protected function sound();
}
class dogs extends animal
{
protected function eat() {
return "meat";
}
public function sound() {
return "bow wow";
}
}
hope my answer made sense to you
classes uses the concept of data abstraction , known as absract data type .
abstract data type is an older term to describe the concepts of stack and queues in terms of their functionality without describing their implementation .
Abstract Data Type (ADT) is a mathematical model with a collection of operations defined on that model.
Also, ADT is a data type whose behavior is defined by set of values and set of operations.
Shortly: abstract means that you can't make objects from the defined class. ex: if you have shape,square and rectangle classes, but you don't want to define any objects from shape so you will mark it as abstract...
after that if the user try to define a new object from shape, he will got compiler error..
This is from Code Complete -Quote:
Abstract data types form the foundation for the concept of classes. In lanuages that support classes, you can implement each abstract data type in its own class. Classes usually involve the additional concepts of inheritance and polymorphism. One way of thinking of a class is as an abstract data type plus inheritance and polymorphism.
So in my opinion, Abstract data type in OO means abstract class.
What is an abstract data type in object oriented programming?
A Class/Abstract data type is a group of properties, and functions
(for accessing data) of anything which we may want to deal with
while solving some problem in an object oriented way.
What is an object?
Object is an interface to a Class/Abstract data type through which we can access its properties and functions. Objects have memories associated with them used for storing data.
An ADT defines a set of data values and a set of operations on these values.
From this post:
ADT is a set of objects and operations, no where in an ADT’s definitions is there any mention of how the set of operations is implemented. Programmers who use collections only need to know how to instantiate and access data in some pre-determined manner, without concerns for the details of the collections implementations. In other words, from a user’s perspective, a collection is an abstraction, and for this reason, in computer science, some collections are referred to as abstract data types (ADTs). The user is only concern with learning its interface, or the set of operations its performs.
Object such as lists, sets and graphs along with their operations can be viewed as abstract data types. ADTs are basically data types that hides its implementation details. Any part of a program that needs to perform an operation on ADT can do so by merely changing the routines that performs the ADT operations. The program that use them (ADT) will not necessarily need to know which implementation was used
ADT is a kind of data structure. Instead of describing the structure of data, it describes the operation on the data.
For example, what is a stack? Maybe a search tree or some linear data structure, but the user doesn't care. The user just cares about "last in first out" (LIFO).
It is just like an interface. Abstract data type in a class is just used to define something i.e. Without body/implementation such as abstract methods. The body will be added where that class will be inherited.
The difference between interface and Abstract class is that we can not add a method with body in interface where as in abstract class, we can add methods/variables with body/value or make it abstract(i.e. Define there and implement where it is overrided).
An abstract class does not form a concrete object in the real world unlike pure implementation classes. Abstract as the name suggestes they hold/define common behaviours of related objects that need to be reused/defined independantly in all related objects.
Take an example of Birds. If you are writing a progrm that will have something to do with the birds, then you'll first have an abstract base class as Bird and each bird deriving from the abstract base class Bird. Do note that abstract class BIRD does not represent a concrete real world object but a type of related objects that is birds!
Lets start with the class-diagram and then some code.
alt text http://ruchitsurati.net/files/birds.png
public abstract class Bird
{
protected string Name = string.Empty;
public Bird(string name)
{
this.Name = name;
}
public virtual void Fly()
{
Console.WriteLine(string.Format("{0} is flying.", this.Name));
}
public virtual void Run()
{
Console.WriteLine(string.Format("{0} cannot run.", this.Name));
}
}
public class Parrot : Bird
{
public Parrot() : base("parrot") { }
}
public class Sparrow : Bird
{
public Sparrow() : base("sparrow") { }
}
public class Penguin : Bird
{
public Penguin() : base("penguin") { }
public override void Fly()
{
Console.WriteLine(string.Format("{0} cannot fly. Some birds do not fly.", this.Name));
}
public override void Run()
{
Console.WriteLine(string.Format("{0} is running. Some birds do run.", this.Name));
}
}
class Program
{
static void Main(string[] args)
{
Parrot p = new Parrot();
Sparrow s = new Sparrow();
Penguin pe = new Penguin();
List<Bird> birds = new List<Bird>();
birds.Add(p);
birds.Add(s);
birds.Add(pe);
foreach (Bird bird in birds)
{
bird.Fly();
bird.Run();
}
Console.ReadLine();
}
}
Abstract type means whose objects does not exist in real world since it does not have
physical entity.
It acts as a base class for concrete class which has physical existance.
e.g.
Shape is an abstract class whereas circle,rectangle are concrete classes.