If I create a class and define a public constructor of it and I also create a child class of the parent class, it also have constructor.
Then how can I call these two constructors from one of the method of subclass? I mean how to call two or more constructor from one method of a child class in php?
In C++:
You can call just by creating a child object.
When you just create a child object it first calls Parent Constructor and then The child Constructor.
Example:
Class Parent {
void Parent :: Parent() {
cout << "I am parent Constructor!" << endl;
}
};
Class Child : Public Parent() {
void Child :: Child() {
cout << "I am Child Constructor" << endl;
}
};
int main() {
Child childobj;
}
Output:
"I am parent Constructor!"
"I am Child Constructor"
For PHP
class Parent {
public function __construct($bypass = false) {
// Only perform actions inside if not bypassing.
if (!$bypass) {
}
}
}
class Child extends Parent {
public function __construct() {
$bypassPapa = true;
parent::__construct($bypassPapa);
}
}
I am answering this based specifically on C++ programming, as I am not certain which OOP language you are using, but I expect that the principles, if not the specific syntax, will apply.
When you define a class with at least one constructor, the compiler will not generate an implicit constructor. As such, if the constructor(s) you define for the base class require parameters, they must be included in a specific call from the constructor in the child class since there will be no parameter free constructor to call.
class Parent
{
public:
Parent(int a,int a)
:a(a),
b(b)
{
cout<<"Parent constructor "<<a<<b;
}
~Parent()
{}
private:
int a;
int b;
};
class Child : public Parent
{
public:
Child()
:c(5) //error: implicit constructor for Parent is not found
{
cout<<"Child constructor "<<c;
}
~Child()
{}
private:
int c;
};
int main()
{
Child x;
return 0;
}
This problem can be corrected by including a call to the Parent constructor within the constructor for the Child class as follows:
.
.
.
Child()
:Parent(3,4), // Explicit call to Parent constructor
c(5)
{
cout<<"Child constructor "<<c;
}
.
.
.
Hope this helps.
In C#;
When you create an instance of subclass, if the base class has a parameter-less constructor, It will be called. But if the base class has parameter constructor, you may call the constructor of that by following syntax.
Class SubClass : BaseClass(...)
{
...
}
In order to call constructor in other methods you need to have a protected method which was called by constructor, then you can call it from another method. Please note that you cannot call constructor from another method because it's a mechanism for instantiating (It should be called when an instance of that type is created)
Related
abstract class A {
abstract inner class B : A() {
init {
// How can I access the outer class?
}
}
}
In this example, this refers to the class B, this#A refers to the parent class. How can I access the outer class?
Test case:
abstract class A {
abstract inner class B : A() {
init {
println("Should display 'Parent': $this") // replace 'this' by something else?
}
}
}
class Parent : A() {
override fun toString() = "Parent"
inner class Child() : B() {
override fun toString() = "Child"
}
}
fun main() {
Parent().Child()
}
In your example, you created two objects - an instance of Parent, and an instance of Child.
Parent().Child()
^ ^
| |
1 2
So there is really only two different things that you can access from the init block of B. You can either access the Parent object using this#A, which is the object associated with the Child object, or the Child object itself using this (or redundantly this#B).
"Accessing the outer class", which presumably you mean A, is not something you can do, because there is not even such an instance of A.
You can however, invoke A's implementations of methods/properties using super#B.xxx (note that it is not super#A. Read it as "super of B"). Perhaps this is what you intended on doing in the first place.
For example, changing A to the following:
abstract class A {
override fun toString() = "A"
abstract inner class B : A() {
init {
println("Should display 'Parent': ${super#B.toString()}")
}
}
}
would print "A".
Note that this actually calls toString on the Child object, not the Parent object. You cannot do the same to the Parent object, because it is a different object. This init is creating the Child object, right?
In summary, this accesses some object that is in scope. super accesses a specific implementation of a method/property up the inheritance hierarchy.
I have this scenario where I have a super abstract class that emits different types of events using Kotlin sealed classes.
These events are modeled as follows.
sealed class BaseEvent {
object ConnectionStarted : BaseEvent()
object ConnectionStopped : BaseEvent()
}
sealed class LegacyEvent : BaseEvent() {
object TextChanged : LegacyEvent()
object TextCleared : LegacyEvent()
}
sealed class AdvancedEvent : BaseEvent() {
object ButtonClick : AdvancedEvent()
object ButtonLongClick : AdvancedEvent()
}
And here are the classes that emit these events
abstract class BaseViewModel<E : BaseEvent> {
private fun startConnection() {
emit(BaseEvent.ConnectionStarted) // <-- Error
}
fun emit(event: E){
//...
}
}
class LegacyBaskan : BaseViewModel<LegacyEvent>() {
fun textChanged() {
emit(LegacyEvent.TextChanged) // <-- Works
}
}
class AdvancedBaskan : BaseViewModel<AdvancedEvent>() {
fun buttonClicked() {
emit(AdvancedEvent.ButtonClick) // <-- Works
}
}
Here, it only works for the subclass and I can emit any event in the LegacyEvent or AdvancedEvent in their associated classes. However, for the BaseBaskan class, I can't emit the events from the BaseEvent although I stated that the generic type E must extend the BaseEvent.
I need each subclass to have access to its own events as well as the superclass events, but not the other subclasses' events.
How can I still emit events from BaseEvent in the base class, while giving each class the access to emit its own events only?
Not sure if you're confused about why it's not letting you emit the item from the base class. Since E could be any subtype of BaseEvent, if your class could emit ConnectionStarted, then it would be violating its contract any time it is declared as a BaseViewModel<AnythingBesidesConnectionStarted>.
Only way I can think of to make this work is have both private and public versions of the emit function. You might have to change code elsewhere in your class that you haven't shown. If there's some function that returns E, you will have to change it so it returns BaseEvent.
abstract class BaseViewModel<E : BaseEvent> {
private fun startConnection() {
emitInternal(BaseEvent.ConnectionStarted)
}
private fun emitInternal(event: BaseEvent) {
//...
}
fun emit(event: E){
emitInternal(event)
}
}
You can't emit BaseEvent.ConnectionStarted in BaseViewModel (and other events as well) because E is not defined yet, so the type system can't be sure that you won't emit events of another subtype breaking generic type invariance.
Just add an overloaded private version, which accepts BaseEvent argument (you'll need some #JvmName annotation to make it compilable for JVM target):
abstract class BaseViewModel<E : BaseEvent> {
private fun startConnection() {
emit(BaseEvent.ConnectionStarted)
}
#JvmName("emitBaseEvent")
private fun emit(event: BaseEvent) {
//...
}
fun emit(event: E) {
emit(event as BaseEvent)
}
}
It looks like you need contravariance, which can be achieved using in. Assuming your base class only has methods such as emit that use type E as parameter type, not as return type, then:
abstract class BaseViewModel<in E : BaseEvent> {
See https://kotlinlang.org/docs/generics.html#use-site-variance-type-projections.
I saw simple class which was look like:
class SomeClass extends Object{
int a;
int b;
...
...
}
Why this class was extended an Object class? As in documentation was written "Because Object is the root of the Dart class hierarchy, every other Dart class is a subclass of Object." in https://api.dartlang.org/stable/2.4.0/dart-core/Object-class.html.
What will happened if we will not extends Object? Or maybe it will be useful in some specific problems?
All dart classes implicitly extend Object, even if not specified.
This can be verified using the following code:
class Foo {}
void main() {
var foo = Foo();
print(foo is Object); // true
}
Even null implements Object, which allows doing:
null.toString()
null.hashCode
null == something
Type 1:
class TestExample {
object Bell {
fun add(){
}
}
Class B{
TestExample.Bell.add()
}
Type 2:
class TestExample {
companion object Bell {
fun add(){
}
}
Class B{
TestExample.add()
}
In this type 1 and type 2, which is static example and which is singleton example? Both behaves similar behavior right?
From official Kotlin docs:
Object declarations
If you need a singleton - a class that only has got one instance - you
can declare the class in the usual way, but use the object keyword
instead of class
Companion objects
If you need a function or a property to be tied to a class rather than
to instances of it (similar to #staticmethod in Python), you can
declare it inside a companion object
I have two classes Class A and Class SRD (Sample classes for understanding the problem. Real classes are different). Both classes have same Function(method1) with same arguments. Both are not derived from different Classes.
Class SRD is the member of Class A. a function in Class A creates a new object for SRD and calls method1(). It should call the mock function. but it calls the actual implementation
I have Written mock classes for both the classes and defined the mock method in both the classes and Wrote EXPECT_CALL in TEST function
class A{
private:
SRD* srd;
public :
bool Method1();
bool MethodX();
SRD* getsrd() {return srd;}
};
bool A :: MethodX()
{
srd.Method1(); // Not Calling Mock Method - Calling Actual
//Implementation
}
bool A::Method1()
{
....
}
class SRD{
public:
bool Method1();
};
class MockSRD : public SRD{
MOCK_METHOD0(Method1, bool())
};
class MockA : public MockA{
MOCK_METHOD0(Method1, bool())
};
bool SRD::Method1()
{
....
}
class TestA : public A {};
TEST_F(TestA, test1)
{
MockSRD srd;
EXPECT_CALL(srd, Method1())
.Times(testing::AnyNumber())
.WillRepeatedly(Return(true));
srd.Method1() //Working fine - Caling mock Method;
MethodX()
}
When i call s1.Method1(), It should call the mock method. how should i do that ?
I don't want to change the production code.
Thanks for taking time to respond the Question . #Chris Oslen & #sklott
I forgot to make the base class method to Virtual. Its worked fine when i change the base class methods