Java - Overwriting existing function - java

Is there a way on "Rewriting" a function.
Pseudo:
function a() {print "B"}
function a() {print "C"}
Output: C

Overriding
class MyClass {
public void myMethod () {
System.out.println("MyClass");
}
}
class MySubClass extends MyClass {
#Override
public void myMethod () {
System.out.println("MySubClass");
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "MyClass"
MySubClass b = new MySubClass();
b.myMethod(); // "MySubClass"
}
}
In this example, MySubClass overrides the inherited method myMethod.
Overloading
class MyClass {
public void myMethod () {
System.out.println("myMethod");
}
public void myMethod (int i) {
System.out.println(i * 2);
}
public void myMethod (String s) {
System.out.println("Hello, " + s);
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "myMethod"
a.myMethod(33); // "66"
a.myMethod("Jeremy") // "Hello, Jeremy"
}
}
In this example, MyClass has multiple definitions of the method myMethod, but they accept different arguments.

Simply rewrite the method in its subclass.
public class Something {
public Something() {
}
public void printHi() {
System.out.println("Hi");
}
}
public class SomethingElse extends Something {
public SomethingElse() {
}
public void printHi() {
System.out.println("I refuse to say hi!");
}
}
Something something = new Something();
something.printHi(); // prints Hi
SomethingElse somethingElse = new SomethingElse();
somethingElse.printHi(); // prints I refuse to say hi!

Related

Java - How to call method class with interface without know class name

I'm new in java, I want to call method class from implemented Class with interface without know class name "ClassA", which only know Object c and I have 2 file.
File (1) CobaInterface.java
package cobainterface;
public class CobaInterface {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ClassA{
public Integer getTwo(){
return 2;
}
}
interface MyInterface {
public void myMethod();
//here interface
public void myMethodFromClassA(Object c);
}
File (2) : ImpementedClass.java
package cobainterface;
public class ImplementedClass extends CobaInterface {
public void myMethodFromClassA(Object c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
How about if I want to call method getTwo() from ClassA without know Class Name, which only know Object c from file (2) as describe in code above. Thanks for advance.
You should use generic types so the implementation knows what the object will be,
interface MyInterface<T> {
public void myMethod();
//here interface
public void myMethodFromClassA(T c);
}
The impl becomes,
package cobainterface;
public class ImplementedClass Implements MyInterface<ClassA> {
public void myMethodFromClassA(ClassA c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
All together,
class Scratch {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ImplementedClass implements MyInterface<ClassA> {
#Override
public void myMethod() {
}
#Override
public void myMethodFromClassA(ClassA c) {
System.out.println(c.getTwo());
}
}
class ClassA {
public Integer getTwo() {
return 2;
}
}
interface MyInterface<T> {
void myMethod();
void myMethodFromClassA(T c);
}
You could also do a cast
System.out.println((MyClass)c.getTwo());
but you will lose all benefit of type saftey.

how to apply generics and access methods of diff class?

I have these two classes
class 1 :
public class MyClass1
{
public void myClass1Print()
{
System.out.println("in myClass1Print");
}
}
class 2 :
public class MyClass2
{
public void myClass1Print()
{
System.out.println("in myClass1Print");
}
}
How can I create a generic method in class 3 so that the method takes the parameters as generic.
class 3 :
public class MyClass3
{
public static void main(String[] args)
{
MyClass3 obj3 = new MyClass3();
MyClass1 obj1 = new MyClass1();
MyClass2 obj2 = new MyClass2();
obj3.methodMyClass3(obj1, obj2);
}
public <T> void methodMyClass3(T exp,T act)
{
System.out.println("obj1===>>>"+exp.myClass1Print());// compilation error
System.out.println("obj2===>>>"+act.myClass2Print());// compilation error
}
}
since the arguments exp and act are not considered as Objects of MyClass1 , MyCLass2
thus Compilatin error is
The method myClass1Print() is undefined for the type T
The method myClass2Print() is undefined for the type T
You have to use an Interface
#FunctionalInterface
public interface GenenericPrint {
void myClassPrint();
}
public class MyClass1 implements GenenericPrint {
#Override
public void myClassPrint(){
System.out.println("print something from Class1");
}
}
public class MyClass2 implements GenenericPrint {
#Override
public void myClassPrint(){
System.out.println("print something from Class2");
}
}
public class MyClass3{
public static void main(String[] args){
MyClass3 obj3 = new MyClass3();
GenenericPrint obj1 = new MyClass1();
GenenericPrint obj2 = new MyClass2();
obj3.methodMyClass3(obj1, obj2);
}
public void methodMyClass3(GenenericPrint exp,GenenericPrint act){
System.out.println("obj1===>>>"+exp.myClassPrint());// no compilation error
System.out.println("obj2===>>>"+act.myClassPrint());// no compilation error
}
}

Calling a method of a class using an argument of a method which is an object of that class

Consider the following classes
Class A{
public void m1(){
System.out.println("test in A.m1()");
}
public void m2(){
//do something a
}
}
Class B{
public void m1(){
//do something b
}
public void m2(){
//do something b
}
}
Class C{
public void m1(){
//do something c
}
public void m2(){
//do something c
}
}
Class T{
public void m3(Object obj1){
obj1.m1();
}
public void m4(Object obj1){
A a=new A();
m3(a);
}
}
So now my question is, is there any way I can send an open object to a method which will detect what type of object it is and call method of that object class. In this example I am hoping to see the output: "test in A.m1()"
You can use Java's Reflection API to query an arbitrary object to see if it has a method named m1 or m2 and then invoke it. But that is pretty ugly.
Is there anything from stopping you using an interface? Example below (where "..." indicates places where you would put your specific implementation):
interface MyMethods {
public void m1();
public void m2();
}
class A implements MyMethods {
public void m1() { ... }
public void m2() { ... }
}
class B implements MyMethods {
...
}
class C implements MyMethods {
...
}
class T {
public void m3(MyMethods obj1) {
obj1.m1();
}
public void m4(Object obj1) {
// Call m3 three times with different object instance types...
A a = new A();
m3(a);
B b = new B();
m3(b);
C c = new C();
m3(c);
}
}

Java reflection when a method has a variable arglist

I've got something along the lines of the following:
public class A {
public void theMethod(Object arg1) {
// do some stuff with a single argument
}
}
public class B {
public void reflectingMethod(Object arg) {
Method method = A.class.getMethod("theMethod", Object.class);
method.invoke(new A(), arg);
}
}
How do I modify that so that I can do the following instead?
public class A {
public void theMethod(Object... args) {
// do some stuff with a list of arguments
}
}
public class B {
public void reflectingMethod(Object... args) {
Method method = A.class.getMethod("theMethod", /* what goes here ? */);
method.invoke(new A(), args);
}
}
A.class.getMethod("theMethod", Object[].class);
Darthenius's suggestion in the comments for the original question worked, once I wrapped my head around how to do it.
public class A {
public void theMethod(ArrayList<Object> args) { // do stuff
}
}
public class B {
public void reflectingMethod(ArrayList<Object> args) {
Method method;
try {
method = A.class.getMethod("theMethod", args.getClass());
method.invoke(new A(), args);
} catch (Exception e) {}
}
}

delegation example regarding java context

What is delegation in Java? Can anyone give me a proper example?
That's delegation - exactly like in the real world:
public interface Worker() {
public Result work();
}
public class Secretary() implements Worker {
public Result work() {
Result myResult = new Result();
return myResult;
}
}
public class Boss() implements Worker {
private Secretary secretary;
public Result work() {
if (secretary == null) {
// no secretary - nothing get's done
return null;
}
return secretary.work();
}
public void setSecretary(Secretary secretary) {
this.secretary = secretary;
}
}
(Added Worker interface to get closer to the Delegator pattern)
If you're referring to the delegation pattern, wikipedia has a great example, written in java.
I believe the longer example of the page above is the best one:
interface I {
void f();
void g();
}
class A implements I {
public void f() { System.out.println("A: doing f()"); }
public void g() { System.out.println("A: doing g()"); }
}
class B implements I {
public void f() { System.out.println("B: doing f()"); }
public void g() { System.out.println("B: doing g()"); }
}
class C implements I {
// delegation
I i = new A();
public void f() { i.f(); }
public void g() { i.g(); }
// normal attributes
void toA() { i = new A(); }
void toB() { i = new B(); }
}
public class Main {
public static void main(String[] args) {
C c = new C();
c.f(); // output: A: doing f()
c.g(); // output: A: doing g()
c.toB();
c.f(); // output: B: doing f()
c.g(); // output: B: doing g()
}
}
Same example as aioobe but changed the class names to more intuitive ones. Deriving analogy to real world examples.
public static void main(String[] args) {
Boss boss = new Boss();
boss.toDeveloper();
boss.f();
boss.g();
boss.toSrDeveloper();
boss.f();
boss.g();
}
interface I {
void f();
void g();
}
class Developer implements I {
public void f() {
System.out.println("Developer: f() is too hard for me.");
}
public void g() {
System.out.println("Developer: g() is not in my domain.");
}
}
class SrDeveloper implements I {
public void f() {
System.out.println("Sr. Developer: Okay, I'll see f()");
}
public void g() {
System.out.println("Sr. Developer: I'll do g() too.");
}
}
class Boss implements I {
// delegation
I i;
public void f() {
i.f();
}
public void g() {
i.g();
}
void toDeveloper() {
i = new Developer();
}
void toSrDeveloper() {
i = new SrDeveloper();
}
}
Here is a simple example of how Delegation is used:
interface IDogBehaviour {
public void doThis();
}
class BarkSound implements IDogBehaviour {
public void doThis() {
System.out.println("Bark!");
}
}
class WagTail implements IDogBehaviour {
public void doThis() {
System.out.println("Wag your Tail!");
}
}
class Dog {
private IDogBehaviour sound = new BarkSound();
public void doThis() {
this.sound.doThis();
}
public void setNewBehaviour( IDogBehaviour newDo ){
this.sound = newDo;
}
}
class DelegationDemo {
public static void main( String args[] ){
Dog d = new Dog();
//delegation
d.doThis();
//change to a new behaviour type - wag tail
IDogBehaviour wag = new WagTail();
d.setNewBehaviour( wag );
//Delegation
d.doThis();
}
}

Categories

Resources