public class ClassA {
int value = 50;
public void display(){
System.out.println("ClassA displaying value:"+ value);
}
}
public class ClassB extends ClassA {
int value = 25;
public void display(){
System.out.println("ClassB displaying value:"+ value);
}
}
public class Test {
public static void main(String[] args) {
ClassA objA = new ClassB();
ClassB objB = new ClassB();
System.out.println(objA.value); --> 50
System.out.println(objB.value); --> 25
objA.display(); --> ClassA Displaying value: 25
objB.display(); --> ClassB Displaying value: 25
}
}
can somebody explain why objA is printing superclass value 50.
In method overriding, at Compile time the object reference is ClassA and it looks for a method Display() in ClassA. If that method is available at ClassA then at runtime actual object created is of ClassB and display() method in ClassB overrides ClassA 's display() method.
But what is happening when we printing the class property "Value" ?
ClassA objA = new ClassB();
System.out.println(objA.value);
Here reference is ClassA and actual object is of ClassB. So I am expecting classB's value: 25. But the value:50 from ClassA is printing.
Please correct if my understanding is wrong..
Thanks in Advance
First, let me correct a little wording mistake:
In method overriding, at Compile time the object reference is ClassA and it looks for a method Display() in ClassA.
No, methods are not called at compile time. They are called at runtime. At runtime, the object is actually an object of ClassB, so it will look for the method in ClassB, which is why the 2 display calls bot print 25.
Okay, now you have to understand the difference between overriding and hiding. The method display is overrides so even if objA is of type ClassA, the method in ClassB is called because objA actually contains an instance of ClassB.
value, on the other hand, is hidden. When you access value, objA is a variable of type ClassA, so it looks for the value of value in ClassA, even though objA contains an object of ClassB.
If you want to override value, you have to make it a method:
class ClassA {
public int getValue() { return 50; }
public void display(){
System.out.println("ClassA displaying value:"+ getValue());
}
}
class ClassB extends ClassA {
public int getValue() { return 25; }
public void display(){
System.out.println("ClassB displaying value:"+ getValue());
}
}
Related
I hope the title is precise enough.
I was wondering, how I can pass a interface implementation to an object in objc language.
In java it would look like:
public interface MyInterface {
void onData();
}
The implementing class
public class ImplementMyInterface {
// ...
// other methods
///
void registerInterface(){
MyInterface myInterface = new MyInterface(){
#Override
public void onData(){
// process data here within the class
}
};
}
}
And in objc?
id myinterface.
How to implement it in the class?
Is there only the possibility to let the class inherit the interface?
Like
interface MyInterface : NSObject
and the implementing class
MyImplementingClass : MyInterface
Or is there another possibility?
Thank you in advance
Objective-C has anonymous functions (blocks), but it doesn't have anonymous classes. So, the only way to implement a protocol (which is the objective-c term for an interface) is to make some class conform to that protocol (using your terminology, make that class "inherit" from that protocol) and add a protocol implementation inside that class' implementation.
I was able to solve my problem.
I was only able to import the MyInterface header file in my ImplementMyInterface.m file, but rather in the ImplementMyInterface.h file.
So everything I could do was inside the ImplementMyInterface.m file.
// ImplementMyInterface.m
#import "MyInterface.h"
// inner class
#interface MyInternalInterface : NSObject<MyInterface>
#property (retain) ImplementMyInterface * implementation;
#end
// the actual class
#implementation ImplementMyInterface
MyInternalInterface * _internalInterface;
+(instancetype) build {
// construct myself
ImplementMyInterface * implementatMyInterface = [[ImplementMyInterface alloc] init];
// init inner class object
_internalInterface = [[MyInternalInterface alloc] init];
// register myself
[_internalInterface setImplementation:implementatMyInterface];
return implementatMyInterface;
}
- (NSString *) theActualData {
return #"The actual data";
}
// end of implementation class
#end
// implementation of inner class
#implementation MyInternalInterface
#synthesize implementation;
- (NSString *) onData {
if(implementation != nil)
return [implementation theActualData];
return #"";
}
// end of ImplementMyInterface.m
Lets suppose I have a class in Objective C, via bridging I want to use in my swift project.
#implementation MyClass
+ (instancetype)startVideo:(NSInt *)videoName
{
return [[MyClass alloc] initWithName:videoName
offset:#"0"]
}
- (instancetype)initWithName:(NSString *)name
offset:(NSString *)offset
{
self = [super init];
return self;
}
Now there are two constructors will be available in the swift version after bridging
class MyClass{
public convenience init!(videoName: String!)
public init(name: String!, offset: String)
}
I derive class from MyClass in my swift project
class MyClass2 : MyClass{
var purposeOfClass: String = "Child class"
}
Create an object of MyClass2 using convenience method
var obj = MyClass2("Swift.mov")
print(obj.purposeOfClass) // You will get exception at this point, because the constructor returned Parent's class object.
Here my question is why the bridging conversion make the static method initializer convenience initializer if the derived class return object can't be checked.
In a Swift init method the truncated parameter name from Objective-C
- (instancetype)initWithFoo:(NSString *)foo
to Swift
init(foo : String)
is mandatory. You have to write
let obj = MyClass2(videoName:"Swift.mov")
print(obj.purposeOfClass)
I have class tructure like this
#interface SuperClass: NSObject
+ (void) someName;
#end
#interface MyClass: SuperClass
#end
There is the case that i only want to call the someName if it is a class method of MyClass not MyClass's superclass. Since [[MyClass class] respondsToSelector:#selector(someName)] return YES if a class or its super response to the selector. How to tell that MyClass doesnt contain tosomeName?
In my application i want to print the string that contains chains of string return from a class method.
Take abve class structure as a example, i want to print something like:
somenameFromSuper.somenameFromClass.someNameFromeSubClass.
if a class doesnot implement someName method, i want to replace it by `notavailable, for ex:
somenameFromSuper.notavailable.someNameFromeSubClass.
_Bool class_implementsMethodForSelector( Class cls, SEL selector )
{
unsigned methodsCount;
Method* methods = class_copyMethodList(cls, &methodsCount);
for (unsigned methodIndex=0; methodIndex<methodsCount; methodIndex++)
{
if (method_getName(methods[methodIndex]) == selector)
{
break;
}
}
free(methods);
return methodsIndex<methodsCount;
}
…
Class classToTest = …;
classToTest = object_getClass(classToTest); // For checking class methods
if (class_implementsMethodForSelector(classToTest, #selector(someName))
{
…
}
else
{
…
}
Typed in Safari.
Edit: Made a function of it. Still typed in Safari.
I am trying to understand Referring to Instance Variables from Apple guide but having issue understudying this, Apple Doc says
...When the instance variable belongs to an object that’s not the receiver, the object’s type must be made explicit to the compiler through static typing. In referring to the instance variable of a statically typed object, the structure pointer operator (->) is used.
Suppose, for example, that the Sibling class declares a statically typed object, twin, as an instance variable:
#interface Sibling : NSObject
{
Sibling *twin;
int gender;
struct features *appearance;
}
As long as the instance variables of the statically typed object are within the scope of the class (as they are here because twin is typed to the same class), a Sibling method can set them directly:
- makeIdenticalTwin
{
if ( !twin )
{
twin = [[Sibling alloc] init];
twin->gender = gender;
twin->appearance = appearance;
}
return twin;
}
Referring to instance variable means, accessing the class instance vars
For example:
#interface ClassA : NSObject
{
int value;
}
- (void) setValue:(int) val;
#implementation ClassA
- (void) setValue:(int) val
{
//here you could access class a value variable like this
value = val;
}
Now accessing other classes variables
take for example this class
#interface ClassB : ClassA
{
ClassA aClass;
}
- (void) setValueInAClass:(int) val;
#implementation ClassB
- (void) setValueInAClass:(int) val
{
//class b could access variables from class a like this
aClass->value = val;
}
Please note that this is very un recommended to do, using the "->" breaks the encapsulation of class a, so dont in 99% of the cases referring to class variables using the "->" is a mistake
I have an Objective-C++ file, and I have two classes: one Objective-C, one C++:
#implementation ClassA
....
// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);
#end
class MyClass : public AnotherClass
{
....
};
This compiles and runs fine with the C++ class up on top, but I'd like to move it to the bottom. When I move it to the bottom I get the error:
Invalid use of incomplete type 'struct MyClass'
Forward declaration of 'struct MyClass'
Regardless of using typedef,struct,#class I get no love. How do I forward declare this class?
Forward declaration of a C++ class does not allow you to use instances of the class, you can just pass them around. (To simplify the example, I have omitted any Objective-C.)
class Something;
void function(void)
{
Something *x; // Ok
x = new Something(); // Error
int z = x->field; // Error
x->method(); // Error
}
class Something : public Other { ... };
void function2(void)
{
Something *x; // Ok
x = new Something(); // Ok
int z = x->field; // Ok
x->method(); // Ok
}
You must put the entire definition of a class before you use it. The forward declaration only allows you to declare variables using the class's type.
So the answer is: what you ask is impossible. (What is wrong with putting the class definition at the top, anyway?)
You can still put methods at the bottom:
class Something {
public:
void method();
};
#implementation ...
...
#end
void Something::method() { ... }
Just add class MyClass Prototype before ClassA.
class MyClass;
....
#implementation ClassA
....
// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);
#end