0

I have learned that Interfaces contain only abstract methods and whatever classes implements these interfaces has to override the methods. In java.lang package,there is an "Interface CharSequence" which has "char charAt(int index)" abstract method.

charAt in following code works fine.in

public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}

If CharAt is an abstract method, how can anyone use the method and pass arguments without any logic in method(as charAt is an abstract method). Please explain how CharAt abstarct method works without any method body(logic). what is the purpose of having Interfaces in JAVA API if all abstract methods in it must be overridden by programmers with their own logic. Am i missing anything.??

Roushan
  • 4,074
  • 3
  • 21
  • 38
  • In Java 8+, interfaces **can** have `default` methods. – Elliott Frisch May 08 '16 at 05:54
  • Please read: http://programmers.stackexchange.com/questions/131332/what-is-the-point-of-an-interface , http://stackoverflow.com/questions/4436087/what-is-the-actual-use-of-interface-in-java , http://stackoverflow.com/questions/4052621/the-purpose-of-interfaces-continued – Chintan May 08 '16 at 05:57

2 Answers2

0

The class String implements the interface CharSequence, so it adds the method logic. Interfaces are useful when you have multiple objects that need to have a common set of methods. For example, in a game, some game objects would need an update and draw method. Then, no matter what object type it is, your program always knows how to update and draw the object. For more information on interfaces refer to: Is there more to an interface than having the correct methods

Community
  • 1
  • 1
CConard96
  • 874
  • 1
  • 7
  • 18
0

The variable you taken i,e String s = "Strings are immutable"; is clearly a string object. In String API it implemented the CharSequence.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
      ....
}

and here is charAt method in String class

public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

so when you invoking the method charAt then String class method charAt get invoked.

source:-https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Roushan
  • 4,074
  • 3
  • 21
  • 38