• Post Reply Bookmark Topic Watch Topic
  • New Topic

class implementation  RSS feed

 
rajareddy dodda
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends

following is my question , i am getting identifier expected error. please let me know the mistake in this program.

public interface xyz{

int a = 10;

}

public class abc implements xyz{

int b=5;
System.out.println(a+b);

}
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by rajareddy dodda:
hi friends


public interface xyz{

int a = 10;

}

public class abc implements xyz{

int b=5;
System.out.println(a+b);

}


If you look ate carefully , this an executable statement so this must be in a method , rigth.

Hope you found your mistake !
 
Dariusz Kordonski
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public interface xyz{

int a = 10;

}

Be aware that it is actually public static final int a. No fields other than public constants are allowed in interfaces. Even though the compiler will add those modifiers for you, it is a good practice to put them in code explicitly. Also, Java code conventions recommend to write constant fields names in uppercase, so A would be better then a





You try to put an execution statement ('System.out.println(a+b);') within a class body. It is not allowed, you have to define a method and put this statement into it, like this:


The statement'int b=5;', on the other hand, will compile, because it is so called initialization statement. It will be executed each time a new instance of your class abc is created (by the way - according to code conventions it would rather be Abc; I know that's just a simple example and I'm being overly scrupulous, but I found out that the more you stick to good practices - even in the simplest examples - the more you see them in your real-life code )


Ooops, Sagar responded quicker... and I gave away the secret :roll:
[ August 07, 2008: Message edited by: Dariusz Kordonski ]
 
rajareddy dodda
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot, i understand my mistake.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!