How to create object of nameless derived class of my abstract class? - java

Consider following Java program:
abstract class Surprising
{
void fun()
{
System.out.println("fun() is invoked");
}
}
class myclass
{
public static void main(String args[])
{
Surprising s=new Surprising() { };
s.fun();
}
}
Here I am creating object of nameless subclass of my abstract class Surprising, not the object of abstract class because it isn't allowed to create object of abstract class in Java.
What is the equivalent C++ program? Is it possible to do this in C++? If yes, how & if no, why not allowed?

Lets say we have the class A:
class A
{
...
};
Now to create a derivative of it, we use e.g.
class B : public A
{
...
};
Now to create an object of an anonymous class we simply don't provide a class name:
class
{
...
} anon_object;
And finally we combine the two ways, inheritance and anonymous classes:
class : public A
{
...
} anon_a_derived_object;

In C++ the Surprising class would not be abstract, because it defines all of its members. If you want an abstract (i.e. not instantiable) class, make at least one of its members pure virtual. Like here:
class Surprising
{
public:
virtual void fun()=0;
};
You can then define the member in an anonymous class of which you create an instance and then invoke the newly defined member function on that instance:
#include <iostream>
int main()
{
class : public Surprising
{
public:
virtual void fun() { std::cout << "Surprise!" << std::endl; }
} inst_;
inst_.fun();
return 0;
}

You cannot do this as on-the-fly as in Java, in the sense of declaring the class as part of the new expression. But you can create a local class inside the function and use it:
void main(int argc, char **argv)
{
class MySurprising : public Surprising {};
MySurprising s;
}

There are several differences between Java and C++ relevant to this question. I tried to produce the C++ code that most closely matches the Java code in question.
#include <iostream>
class Surprising // class is abstract since it has pure virtual method
{
public:
virtual void fun() = 0; // pure virtual method makes the class abstract
};
// we can define the pure virtual method, but not in class
inline void Surprising::fun()
{
std::cout<<"fun() is invoked\n";
}
int main()
{
struct : Surprising // anonymous derived class
{
void fun() // we must provide an implementation of fun()
{ // for otherwise this class remains abstract and
Surprising::fun(); // cannot be instantinated
}
} s; // object of anyonmous class
s.fun();
}

Related

What is the equivalent of :: operator in java?

When accessing a function from another class in c++,
we can write: classA::fct();
Is there an equivalent operator in java?
If not, how can we access a function from another class in java?
Well the ::-operator (Scope Resolution Operator) in C++ allows you to resolve ambiguous calls/references to identifiers. However, in java there are no independent functions as all functions are actually methods (members) of a class. As such there are no need for this operator, have a look here for differences between Java and C++ classes.
I am guessing you are attempting to access a member (possibly static) of a class, in which case you'd use the .-operator as exemplified in Mwesigye's answer or as follows:
public class AB {
public static void main(String[] args) {
B myB = new B();
myB.printA();
}
}
public class A {
public static int getInt() {
return 4;
}
}
public class B {
public void printA() {
System.out.println(A.getInt()); // output: 4
}
}
Here the .-operator is used to access printA() from the instantiated object myB (instantiated from class B). It is also used to access the static method getInt() whose implementation is tied to class A rather than any object of A. More info can be found here.
Take an example of a Class Student with methods what you call functions in c++
eg.
class Student{
//a non static method
public void getFees(){
//your logic
}
public static void deleteSubject(){
// your logic
}
}
class Club{
//create a new instance of student class
Student student = new Student();
public void printData(){
//access a non static method
student.getFees();
//accessing a static method
new Student().deleteSubject();
}
}
Hope this will help.

C# overriding methods in object declaration like in Java

but I've been programming in Java so I know you can Override methods in Object's instantiation
private MyObject myObject=new MyObject(){
#Override
public void myMethod(int args){
.
.
.
}
}
can somebody show me how to do this in C# please.. Thanks
Unlike Java where all instance methods a virtual ones, in C# you have to put virtual keyword explicitly:
public class MyObject {
...
// in order to be overriden in a derived class, base method should be
// explictly declared as virtual or abstract
public virtual void myMethod(int args){
...
}
...
}
In C# override is a keyword as well, not just an attribute:
// class can't be declared locally, but explictly
public class MyOverridenObject: MyObject {
...
// override is a mandatory keyword in the context
public override void myMethod(int args){
...
}
}
Finally, C# doesn't allow implementing classes locally, so you have to declare the class explicitly (MyOverridenObject in the code above) and then use:
// Finally, you can assign an overriden class to the private field
private MyObject myObject = new MyOverridenObject();
so I know you can Override methods in Object's declaration
This isn't object declaration but class instantiation. And this feature doesn't exist in C# .
Therefore, you can only override polymorphic methods on class declarations:
public class A
{
public virtual void DoStuff() {}
}
public class B : A
{
public override void DoStuff() {}
}

Difference between these 2 codes?

I was wondering why this piece of JAVA code produces a different output than the same code in C++.
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A(){
this->Foo();
}
virtual void Foo()
{
cout << "A::Foo()" << endl;
}
};
class B : public A
{
public:
B()
{
this->Foo();
}
virtual void Foo()
{
cout << "B::Foo()" << endl;
}
};
int main(int, char**)
{
B objB;
system("pause");
return 0;
}
This produces the output:
A::Foo()
B::Foo()
The JAVA code is:
public class Testa {
public Testa()
{
this.Foo();
}
public static void main(String[] args)
{
Testb b = new Testb();
}
void Foo()
{
System.out.println("A");
}
}
class Testb extends Testa {
public Testb()
{
this.Foo();
}
#Override
void Foo()
{
System.out.println("B");
}
}
This code produces only
B
B
Why is this output different in this case?
The difference is in the handling of polymorphism during construction. In Java, the dynamic type of the object is that of the derived class right away, allowing you to call member function even before the constructor gets a chance to set the member variables. This is bad.
C++ has a different approach: While the constructor runs, the type of the object considered to be the one of the class that the constructor belongs to. All calls to member functions are resolved statically according to that assumption. Consequently, the constructor of A calls A::foo(), while the constructor of B calls B::foo().
Edit
The first part of my answer was given before the Java Testa constructor was included.
In the Java code, you don't have a Testa constructor defined as in your C++ code. That explains why only one B is printed in Java.
But even if you did, to make the code more equivalent:
public Testa()
{
this.Foo();
}
It would print
B
B
Because in Java polymorphism works even when the method is called from the constructor. But that's not a good idea to do that, because the child part of the object Testb will still be uninitialized when the method Foo is called in Testb.

Difficulties in understanding a Java implementation with nested functions (and coding it in C++) [duplicate]

This question already has answers here:
Does C++0x support Anonymous Inner Classes?
(4 answers)
Closed 10 years ago.
I look at a piece of Java code I would like to see how it would be implemented in C++:
public interface IThing {
public void method1();
// more (virtual methods)
}
public interface IThingFactory {
public IThing getThing(ThingType thing);
}
public interface IFactory<T> {
public T createInstance();
}
public class A {
A(ThingType thingType, IFactory<IThing> thingFactory, ...) {
// ...
}
static A create(ThingType thingType, final IThingFactory thingFactory) {
return new A(new IFactory<IThing>() {
{
public IThing createInstance()
{
return thingFactory.getThing(thingType);
}
}, new IFactory< ... >()
{
public IAnother createInstance()
{
return anotherFactory.getAnother(anotherType);
}
});
}
// ...
}
I hope above code (not complete) illustrates what I try to find out. My problem is
how that would be done in C++.
Mainly I do not understand the implementation of the createInstance inside in A constructor call (as it seems for me still incomplete), like an anonymous function implementation. I do not see a way how I could implement the createInstance method in C++ in a way so that the object of (abstract) type IFactory<IThing> is defined, because in this way the (virtual) method createInstance is still pure. Or could that be done with some kind of lambda function?
Can somebody show me a way how this would be coded in C++? Thanks for the info!
The Java Language Spec writes:
Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (ยง15.9.5) and creates an instance of it.
That anonymous class is a subclass of the class named in the class instance creation expression (in your case: IFactory).
A special feature of anonymous classes is that they may access final variables of surounding scopes. This is implemented by providing their values to the constructor of the anonymous subclass, which then stores them in final fields in that subclass.
A direct translation to C++ would therefore be to instantiante a named subclass that takes these values as constructor parameters. Depending on what the code actually does, a more idiomatic translation might exist.
In C++ you can also have anonymous class, just as you can have anonymous struct (class is the same as struct with private).
However, I think you'd better not use this, because we can not explicitly make the anonymous class inherit from class B, in the main function it is casted to B* which is very ugly, what's more, new operator can not be directly applied to the anonymous class. Thus the anonymous instance c is allocated on stack, it will be deleted when the program runs out of scope, and will cause problem.
Using a named subclass is the standard way.
#include <iostream>
using namespace std;
// class B is a pure virtual class which is equivalent to interface in java.
class B
{
public:
virtual int F() = 0;
};
class A
{
public:
B * bb;
public:
A(B* b);
};
A::A(B*b)
{
bb = b;
}
int main()
{
class{public: virtual int F(){return 10;}} c;
A a((B*) &c);
cout<<a.bb->F()<<endl;
}

C++ abstract classes

I am new to C++, I coded in Java for an year. The equivalent in C++ for interfaces and abstract classes alike is only abstract classes. Is that supposed to be a handicap while doing factory design? There are many times I want to leave out the defining the methods to the inheriting classes and I want to enforce that.
If you define like this you can have what you want:
class A {
public:
virtual void pure_virtual(int param1) = 0;
virtual ~A() { };
};
EDIT: Thanks Nikolai and Mike!
Java interfaces are best translated as C++ abstract classes. In Java (as far as I know) a interface is merely a subset of an abstract class anyway, except it allows "multiple inheritance" which C++ has in all cases anyway.
class thing_interface {
public:
virtual ~thing_interface() {}
virtual void foo() =0; //pure virtual function
};
class other_interface {
public:
virtual ~other_interface () {}
virtual void bar() =0; //pure virtual function
};
class thing_impl : public thing_interface, public other_interface {
protected:
int member;
public:
thing_impl() : member(0) {}
virtual ~thing_impl() {};
virtual void foo() { std::cout << "FOO!\n";}
virtual void bar() { std::cout << "BAR!\n";}
};
The =0 syntax means it is not defined in the interface, but must be defined in classes that fulfill the interface. Also note that if you have any virtual function, you almost always want a virtual destructor as well. C++ will tell you an error if you try to make a thing_interface by itself, since there's no implementation functions.
It's not really a handicap, since I can't think of anything Java can do here that C++ can't.
In terms of interface/abstract classes you wont feel handicap. You should read about C++ pure virtual functions and abstract classes.
To have interface in C++, here is the sudo code:
class MyInterface {
virtual void func1() = 0;
virtual int func2(int x, int y) = 0;
}
class MyAnotherInterface {
virtual void func3() = 0;
virtual int func4(int x, int y) = 0;
}
To have abstract class in C++, here is the sudo code. You can see it only implements one function from the interface above. So you cannot create instance of it.
class MyAbstract : public MyIterface {
void func1() {
printf("in func1");
}
}
Now the actual concrete class:
class MyConcreteClass : public MyAbstract, public MyAnotherIterface {
int func2(int x, int y) {
printf("func2 x=%x,y=%y",x,y);
}
void func3() {
printf("in func3");
}
int func4(int x, int y) {
printf("func4 x=%x,y=%y",x,y);
}
}
There are some issues when you are using Multiple inheritance as I am using for MyConcreteClass. But if you only have one base with member variables and other base classes contain only pure virtual functions then this pattern acts exactly like Java, where the class containing some methods and member variables maps to extends and other classes which contain only pure virtual functions maps to `implements'.
In our example, Java equivalent code is
class MyConcreteClass extends MyAbstract implements MyAnotherInterface {
public int func2(int x, int y) {
System.out.print(String.format("func2 x=%x,y=%y",x,y));
}
public void func3() {
System.out.print("in func3");
}
public int func4(int x, int y) {
System.out.print(String.format("func4 x=%x,y=%y",x,y));
}
}
Where you feed handicap
The only other place where I feel handicap when coming from Java is generics. C++ has templates for that, but they some serious limitations.

Categories

Resources