I have 5 different class. These are ASeat, BSeat, CSeat, Seat, Appointment. ASeat, BSeat, CSeat is inheriting the Seat class. Appointment class determines which class to choose(ASeat,BSeat,CSeat). Lets say if value(jobType) equals 1 we will get ASeat as parameter, if it equals 2 BSeat as parameter and if it equals 3 we will get CSeat as parameter.
I've tried code like below but It didn't work
How can I do that?
Sample code from Appointment class(Constructor):
public Appointment(jobType,Seat seat) {
if(jobtype==1){
seat.ASeat.function1();
}
}
I want to define class by a jobType
I've written a few examples to better understand below
public Appointment(1,ASeat aseat) {
ASeat.function1();
}
public Appointment(2,BSeat bseat) {
bseat.function2();
}
public Appointment(3,CSeat cseat) {
cseat.function3();
}
If i use like below. it would so unnecesary and gibbish
public Appointment(Dentist dentist, Patient patient,int jobType,ASeat aseat,BSeat bseat,CSeat cseat) {
if(jobType==1){
aseat.function1();
}
if(jobType==2){
bseat.function2();
}
if(jobType==3){
cseat.function3();
}
}
It feels like you want to use the FactoryPattern.
A clear example is defined here:
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
If I understood correctly, all subclasses have a method with the same signature and you want to call that method.
If you want to call it, you need to extract it in the superclass and override it:
public class Seat{
public void function(){
throw new UnsupportedOperationException ("Not implemented for superclass");
}
}
public class ASeat extends Seat{
#Override
public void function(){
//Your code
}
}
//where you call it
seat.function();
If the superclass is abstract, you could even use an abstract method:
public abstract class Seat{
public abstract void function();
}
public class ASeat extends Seat{
#Override
public void function(){
//Your code
}
}
//where you call it
seat.function();
Related
This might (most certainly will) sound stupid, but I am stuck and I cant find a proper solution to my problem.
I have a superclass and two sub classes extend it. On the parent class based on a condition I want to call the method from either of the two classes. This is inside a loop, so instead of doing the same check I decided to do the check once, create an object from the super class and then change the object to either one of the two sub classes. i.e.
public class Parent{
public void method() {
Parent object=new Parent();
if(a==b) {
object=new Child_A();
}else {
object=new Child_B();
}
for() {
object.method();
}
}
public void method() {
//empty method. need it just to compile
}
}
public class Child_A extends Parent{
public void method() {
//do something useful
}
}
public class Child_A extends Parent{
public void method() {
//do something useful
}
}
I had to write the Parent.method(), cos otherwise the compile would complain that there is no method() method on class Parent.
So with this, the method called is not one of the children,but the parents method.
I have read that objects need to be assigned directly to the class, like Childen_A object=new Childen_A. The thing is that I would like to use the same command for both cases (object.method()) no matter which class it refers to. Strange thing is that during debug, i see that object is of type Child_A, nevertheless the super method is called.
I know that the solution would be to create two different objects, one for each sub class, but that would make my code a bit more ugly and i would have to use the if statement inside the loop.So the correct way of doing it must be
public void method() {
for() {
if(a=b) {
Child_A object=new Child_A();
object.method();
}else {
Child_B() object=new Child_B();
object.method();
}
}
}
Is there a way to avoid the if statement inside the loop? Thanks
Your code should be
public class Parent {
public void method() {
}
// OR
public abstract void method(); // and make the class abstract as well
}
public class Child_A extends Parent {
#Override
public void method() {
//do something useful
}
}
// same with Child_B
In the following example, the call FirstChildclass first; first.someMethod(); will do the same as SecondChildclass second; second.someMethod();. Or am I wrong?
class Superclass {
public void someMethod() {
//do something
}
}
class FirstChildclass extends Superclass {
#Override
public void someMethod() {
super.someMethod();
}
public void someOtherMethod() {
//do something else
}
}
class SecondChildclass extends Superclass {
public void someOtherMethod() {
//do something else
}
}
Is there a reason why one will implement it like in FirstChildclass? Because I have seen many implementations like in FistChildclass and am wondering why anyone would do it.
If you ask about the difference between:
#Override
public returnType someName() {
return super.someName();
}
and not overriding it. There is no difference as well as there is no sense in doing it.
You should call super.someName() just in case you want to extend the original method.
Watch out! If you have a constructor you want to use in a child class, but you don't need any additional behavior, you'll call super(arguments).
This is about your design. Override means you wanna change the already existing implementation which is inherited from the parent.
If you are not doing anything different then you don;t want to do the
#Override
public void someMethod() {
super.someMethod();
}
That is useless.
#Override
public void someMethod() {
// do some other logic
super.someMethod();
// do some other logic
}
This is perfectly ok :) Because you are doing some tasks other than the parent's implementation.
I have to send this to another class
I need void in my activity like this:
mStrawberry.foo(this)
and inside Strawberry
public class Strawberry{
public Strawberry(){}
foo( ????? thisVariable ){
//work with this...
}
}
I know this is MainActivity.this bud I have to use different class not only MainActivity...
Thank you for the reply
Just declare a parameter of the appropriate type (whatever this is in the code mStrawberry.foo(this)):
public class Strawberry{
public Strawberry(){}
foo(TheRelevantType thisVariable ){ // ***
thisVariable.doSomething(); // ***
}
}
In the above, I've used TheRelevantType.
I know this is MainActivity.this bud I have to use different class not only MainActivity...
If you need to have a method that accepts instances of two different classes, you do that by having both classes implement an interface with the common aspects you need to use:
interface ActivityCommon {
void doSomething();
}
class ThisActivity implements ActivityCommon {
public void doSomething() {
System.out.println("This is ThisActivity's doSomething");
}
}
class ThatActivity implements ActivityCommon {
public void doSomething() {
System.out.println("This is ThatActivity's doSomething");
}
}
class Strawberry {
foo(ActivityCommon common) {
common.doSomething();
}
}
...and/or use a common base class, which looks very similar:
class ActivityBase extends Activity { // Or whatever the base should be
abstract void doSomething();
}
class ThisActivity extends ActivityBase {
#Override
public void doSomething() {
System.out.println("This is ThisActivity's doSomething");
}
}
class ThatActivity extends ActivityBase {
#Override
public void doSomething() {
System.out.println("This is ThatActivity's doSomething");
}
}
class Strawberry {
foo(ActivityBase activity) {
activity.doSomething();
}
}
I'll show the rudimentary approach of Object as you seem to be unaware of how Java works. You can use Generics as well but it will go over your head and you will blunder around before actually understanding how it works.
foo(Object passedActivity){
//Object is the base class to all classes in java and can refer to anything
if(passedActivity instanceof FirstActivity){
FirstActivity fref = (FirstActivity)passedActivity;
//modify the data now using fref
//fref.finish(); or any other similar thing
}else if(passedActivity instanceof SecondActivity){
SecondActivity sref=(SecondActivity)passedActivity;
//modify using sref now
//sref.finish(); or any other similar thing
}else{
Log.d("Error","Please pass a valid Activity");
}
}
I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :
I wanted to implement a method in a abstract class that is called by the inherited classes and uses their values.
For instance:
abstract class MyClass{
String value = "myClass";
void foo(){System.out.println(this.value);}
}
public class childClass{
String value="childClass";
void foo(){super.foo();}
}
public static void main(String[] args){
new childClass.foo();
}
This will output "myClass" but what I really want is to output "childClass". This is so I can implement a "general" method in a class that when extended by other classes it will use the values from those classes.
I could pass the values as function arguments but I wanted to know if it would be possible to implement the "architecture" I've described.
A super method called by the inherited class which uses the values from the caller not itself, this without passing the values by arguments.
You could do something like this:
abstract class MyClass {
protected String myValue() {
return "MyClass";
}
final void foo() {
System.out.println(myValue());
}
}
public class ChildClass extends MyClass {
#Override
protected String myValue() {
return "ChildClass";
}
}
and so on
This is a place where composition is better than inheritance
public class Doer{
private Doee doee;
public Doer(Doee doee){
this.doee = doee;
}
public void foo(){
System.out.println(doee.value);
}
}
public abstract class Doee{
public String value="myClass"
}
public ChildDoee extends Doee{
public String= "childClass"
}
...
//Excerpt from factory
new Doer(new ChildDoee);
I believe you are asking whether this is possible:
public class MyClass {
void foo() {
if (this instanceof childClass) // do stuff for childClass
else if (this intanceof anotherChildClass) // do stuff for that one
}
}
So the answer is "yes, it's doable", but very much advised against as it a) tries to reimplement polymorphism instead of using it and b) violates the separation between abstract and concrete classes.
You simply want value in MyClass to be different for an instance of childClass.
To do this, change the value in the childClass constructor:
public class childClass {
public childClass() {
value = "childClass";
}
}
Edited:
If you can't override/replace the constructor(s), add an instance block (which gets executed after the constructor, even an undeclared "default" constructor):
public class childClass {
{
value = "childClass";
}
}