JAVA eclipse different ways implement INTERFACE


interface MyInterface {
	void sayHello();
}

class ClassOne {
	static void methodThatCallInterfaceMethod(MyInterface i) {
		i.sayHello();
	}
}

class ClassTwo implements MyInterface {
	static void sayGoodBye() {
		System.out.println("hi - for METHOD REFERENCE CALLING");
	};

         @Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("Good Morning FROM CASS THAT DIRECTLY IMPLEMENTS INTERFACE ");
	}

	MyInterface getMyInterface() {
		return this;
	}
}

class ClassThree {
	static ClassTwo getInstanceOfClassTwo() {
 		return new ClassTwo();
	}
}

public class Main implements MyInterface {
	public static void main(String[] args) {
		Main InstanceOfMain = new Main();
		//METHOD 1
		InstanceOfMain.methodThatServeAsABridgeToExecuteinMainStaticMethod();
		//METHOD 2
		ClassOne.methodThatCallInterfaceMethod(new Main());
		//METHOD 3
		ClassOne.methodThatCallInterfaceMethod(new MyInterface() {
			@Override
			public void sayHello() {
				// TODO Auto-generated method stub
				System.out.println("Good morning from INNER CLASS");
			}
		});
		//METHOD 4
		ClassOne.methodThatCallInterfaceMethod(() -> System.out.println("Hi from LAMBDA IMPLEMENTATION"));
		//METHOD 5
		ClassOne.methodThatCallInterfaceMethod(ClassTwo::sayGoodBye);
		ClassTwo InstanceClassTwo = new ClassTwo();
		//METHOD 6
		ClassOne.methodThatCallInterfaceMethod(InstanceClassTwo);
		//METHOD 7
		ClassOne.methodThatCallInterfaceMethod(InstanceClassTwo.getMyInterface());
		//METHOD 8
		ClassOne.methodThatCallInterfaceMethod(ClassThree.getInstanceOfClassTwo());
		MyInterface instanceCreatedToStoreAnnonymousInnerClass = new MyInterface() {

			@Override
			public void sayHello() {
				// TODO Auto-generated method stub
				System.out.println("hi from ANNONYMOUS INNER CLAS ASIGNED TO VARIABLE");
			}

		};
		ClassOne.methodThatCallInterfaceMethod(instanceCreatedToStoreAnnonymousInnerClass);
		ClassOne.methodThatCallInterfaceMethod(()->InstanceOfMain.methodInsideMainClass());
		
	}
	void methodInsideMainClass () {
		System.out.println("hi from CLASS INSIDE MAIN CLASS");
	};

	void methodThatServeAsABridgeToExecuteinMainStaticMethod() {
		ClassOne.methodThatCallInterfaceMethod(this);
	}

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("hi from Main INSIDE CLASS");
	}
}

Comment

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *