Reputation: 522
I have studied that
"A class that implements an interface must implement all the methods declared in the interface"
I am doing the study of CharSequence from this link here CharSequence having 4 methods, according to the definition of the interface a class must implement all methods of the interface.
I have created one class and implemented the CharSequence interface
but here I am not overriding the "toString()" method and working fine.
I want to know that my code is not giving any error when I am not overriding the "toString()" but it is giving an error if I am not implementing the others method.
below code is working for me but I think it should give an error.
import java.util.*;
import java.lang.*;
public class Charsequence {
public static void main(String args[]){
System.out.println("hello...");
}
}
class Subsequence implements CharSequence{
public char charAt(int index){
return '1';
}
public int length(){
return 1;
}
public CharSequence subSequence(int start, int end){
return "" ;
}
/*public String toString(){
return "";
}*/
}
sorry for the bad English.
Thank you:)
Upvotes: -3
Views: 227
Reputation: 2017
In java, every class by default extends Object
class in java. The Object
class already has a default implementation for the toString()
method. So every class created in java has default parent class i.e. Object class.
In your case, lets say your class name is Test, Test is using the default implementation of toString() method provided in Object class.
During compilation, java generates .class file for each class. If you see the code of Test.class
file it will look like:
class Test extends Object implements CharSequence{
// YOUR CODE
}
If you want to provide implementation of toString()
, you can override it in your class.
Upvotes: 1
Reputation: 1
All the Java classes extend a predefined class called Object
. The Object class has a few methods defined for you, one of them being toString()
. If we do not define a toString()
in our own class, then the Object
class's toString()
is used.
However, if we are implementing an interface, we must define the methods declared in that interface. If we do not wish to define those methods in the implementing class, it must be declared as abstract
.
Upvotes: 0
Reputation: 147164
toString
is implemented in java.lang.Object
. To be non-abstract, a method just needs an implementation. This even if the the method is implemented in a super class of the class that implements the interface.
In some case you may get a synthetic method in the subclass if there are covariant return types.
Upvotes: 1
Reputation: 2239
All classes have a toString()
method because they inherit Object#toString
, so it is actually "implemented". You should however override it and implement it properly as the CharSequence documentation specifies.
Upvotes: 1
Reputation: 385
All classes in Java extend Object
class.
This is because the Object class implements toString()
.
Upvotes: 1