Vulcan
Vulcan

Reputation: 29

How can I do this in Java? (REL. TO FUNCTIONS)

How can I make a function like String.toUpperCase() , where suppose I make a function Character.isVowel()

Where, I'll simply have to write 'A'.isVowel() and get a boolean result; just like "code".toUpperCase(); which gives me output , CODE.

Only if possible ; can you tell me how can I do so?

Upvotes: 0

Views: 117

Answers (3)

NelDav
NelDav

Reputation: 910

I am not sure what you want to know. If you only want to create a upper case string out of a lower case string use toUpperCase(). Or do you want to know how to extend the String class? Suraj Gautam answerd this question in the comments:

String is an immutable class. You cannot extend it.

Upvotes: 0

LWChris
LWChris

Reputation: 4211

Methods that look like instance methods although they are not part of the actual class are called "Extension methods". Java does currently not support them. See also this question.

Upvotes: 0

gthanop
gthanop

Reputation: 3311

You cannot do this by extending Character because it is a final class (you cannot extend it), but even if you could, you could not just simply cast for example your character to the subclass (you would had to make a corresponding constructor for example).

You could however try something like:

public class Main {

    //Supports only english vowels (uperrcase, or lowercase):
    public static boolean isVowel(final int codePoint) {
        return "aeiouyAEIOUY".indexOf(codePoint) >= 0;
    }

    public static void main(final String[] args) {
        System.out.println(isVowel('A')); //true.
        System.out.println(isVowel('b')); //false.
    }
}

but again you will have to define all the vowels of all languages manually (both uppercase and lowercase).

I also checked regexes in Java, but did not find anything about a Vowel class for example.

Upvotes: 1

Related Questions