Saturday, November 16, 2013

Java Interface implementation example

Write a class that implements the CharSequence interface found in the java.lang package. Your implementation should return the string backwards. Select any sentence. Write a small main method to test your class.

SOLUTION: 

 
package assignment3;

public class InterfaceImplementationExample {
 
 public static void main(String args[]) {
  //Creating object
        CharSequenceDemo s =
            new CharSequenceDemo("This is SHAEED.");

        //Printing the reverse string
        for (int i = 0; i < s.length(); i++) {
            System.out.print(s.charAt(i));
        }
        System.out.println("");
    }
}

class CharSequenceDemo implements CharSequence {
 private String s;
    public CharSequenceDemo(String s) {
        this.s = s;
    }
  
    private int fromEnd(int i) {
        return s.length() - 1 - i;
    }

    public char charAt(int i) {
        return s.charAt(fromEnd(i));
    }

    public int length() {
        return s.length();
    }
    
   public CharSequence subSequence(int start, int end) {
        return "SHAEED KHAN";
    }
}

No comments:

Post a Comment