Comparison of Java ʻinterface and Swift
Protocol`
・ Basic information engineer exam preparation -Comparison of similarities between Java and Swift
main.java
public class Main {
interface sampleInterface{
String sampleFunction(String a, String b);
}
public static void main(String[] args) throws Exception {
/*When implementing an interface in a class, write implements*/
class A implements sampleInterface{
public String sampleFunction(String a, String b){
return "「" + a + ""When"" + b + "Is the argument of sampleFunction defined in classA";
}
}
class B implements sampleInterface{
public String sampleFunction(String a, String b){
return "「" + a + ""When"" + b + "Is the argument of sampleFunction defined in classB";
}
}
A a = new A();
B b = new B();
System.out.println(a.sampleFunction("c","d"));
System.out.println(b.sampleFunction("e","f"));
}
}
"C" and "d" are the arguments of sampleFunction defined in classA
"E" and "f" are the arguments of sampleFunction defined in classB
sample.swift
//protocol
protocol SampleProtocol{
func sampleFunction(_ a:String, _ b:String) -> String
}
// class A
class A:SampleProtocol{
func sampleFunction(_ a:String, _ b:String) -> String{
return "「\(a)"When"\(b)Is the argument of sampleFunction defined in classA"
}
}
// class B
class B:SampleProtocol{
func sampleFunction(_ a:String, _ b:String) -> String{
return "「\(a)"When"\(b)Is the argument of sampleFunction defined in classB"
}
}
var a = A()
var b = B()
print(a.sampleFunction("c","d"))
print(b.sampleFunction("e","f"))
"C" and "d" are the arguments of sampleFunction defined in classA
"E" and "f" are the arguments of sampleFunction defined in classB
Recommended Posts