Consider an interface and its implementation,
interface A {
int a;
default void add() {
a = a+10;
}
public void sub();
}
class X implements A {
public sub() {
a = a-5;
}
}
I have to use the variable a in sub() function of class X. How can I do?
All variables declared inside interface are implicitly public static final variables(constants).
From the Java interface design FAQ by Philip Shaw:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.
Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!
The field a in the interface A always final and static and it isn't supposed to be modified in any way including reassigning it in an instance method.
Interfaces don't have the state. Abstract classes may.
abstract class A {
protected int a;
public void add() {
a += 10;
}
public abstract void sub();
}
final class X extends A {
public void sub() {
a -= 5;
}
}
I would use an abstract class instead of an interface. That way the variable can be modified by the extending class.
abstract class A{
int a=10;
void add(){
a=a+10;
}
public abstract void sub();
}
class X extends A{
public void sub(){
a=a-5;
}
}
Yes, We can use abstract class.
Since in interface variables declared are by default final.
Code with Interface
Code with Abstract Class
Related
Can you declare an abstract variable type in an abstract class? I am receiving an error when I put this line of code in. I can declare a variable that is final and not final but I am not sure if I should be able to declare a variable that is abstract. What would be the real advantage between an interface and an abstract class?
Error Code:
abstract int myScore = 100; <-- Causes an error
Code:
public abstract class GraphicObject {
int home = 100;
String myString = "";
final int score = 0;
abstract void draw();
abstract void meMethod1();
abstract void meMethod2();
int meMethod3() {
return 0;
}
}
"Can you declare an abstract variable type in an abstract class?"
No, according to the JLS (http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1).
Why should it be abstract if you can't implement variables?
Abstract methods only mean that they must be implemented further in your code (by a class that extends that abstract class).
For variable that won't make any since they keep being the same type. myscore will always be an int.
You may be tinking about override the value of myscore by the class that extends that abstract class.
An abstract method is a method that doesn't have a body. This is because it's meant to be overridden in all concrete (non-abstract) subclasses and, thanks to polymorphism, the abstract stub can never be invoked.
Given the above, and since there is no polymorphism for fields (or a way to override fields at all), an abstract field would be meaningless.
If what you want to do is have a field whose default value is different for every subclass, then you can assign its default value in the constructor(s) of each class. You don't need to make it abstract in order to do this.
No, abstract is used so that methods can only be implemented in subclasses. See http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You cannot declare an abstract variable in Java.
If you wish to declare a variable in a super-class, which must be set by its sub-classes, you can define an abstract method to set that value...
For example:
public abstract class Foo {
Object obj;
public Foo() {
init();
}
protected void init() {
obj = getObjInitVal();
}
abstract protected Object getObjInitVal();
}
public class Bar extends Foo {
#Override
protected Object getObjInitVal() {
return new Object();
}
}
Base on "AlonL" reply :
You can do this too
public abstract class Foo {
Object obj;
public Foo() {
init();
}
abstract protected void init();
}
public class Bar extends Foo {
#Override
protected void init() {
obj = new Object();
}
}
I have a base class and subclass. Base class has common methods and its implementation which I want to use in subclass but I want to use subclass member variable instead of superclass. I do not want to rewrite the same method in subclass. Is there a way in Java to achieve this.
You could create a protected setter on the member variable & then override the value of the super's variable within the constructor of the subclass:
class Animal {
private String voice = "Oooo";
protected void setVoice(String voice) {
this.voice = voice;
}
public void speak() {
System.out.println(this.voice);
}
}
class Dog extends Animal {
public Dog() {
setVoice("woof");
}
}
You can use a method to access the member and override it in subclasses.
Class A{
public void DoStuff(){
int aux = getResource;
/*cool things with aux*/
}
protected int getResource(){
return internal_member;
}
private int internal_member;
}
Class B extends A{
private int another_member;
#Override
public int getResource(){
return another_member;
}
}
But take into account that this will not prevent people chaging class A from using the member directly, It might be better to create a base class for the members and the getters.
Another Option, as some people outlined before is to have the data member in the base class as protected and initialize it in the subclass:
Class A{
public void DoStuff(){
/*cool things with internal_member*/
}
protected List internal_member;
A(){internal_member = /*Set here a value*/}
}
Class B extends A{
B(){internal_member = /*Set a different value here! you can even declare a member and assign it here*/}
}
You can use constructors with arguments if you need.
How would you declare a static variable in Super and instantiate it in subclass
Example
class A
{
static Queue<String> myArray;
public void doStuff()
{
myArray.add(someMethod.getStuff());
}
}
class B extends A
{
myArray = new LinkedList<String>();
}
class C extends A
{
myArray = new LinkedList<String>();
}
Obviously this doesnt work. But how would you go about declaring a variable; then doing some common functionality with the variable in the super class; Then making sure each subclass gets it own static LinkedList?
You can't do stuff along these lines. The closest you can do is to have an abstract (non-static) method in the superclass and do some stuff with it.
But in general, you cannot force subclasses to do anything static, and you cannot access subclasses' static fields from a superclass like you're trying to do.
Since, you have subclass-specific properties to manipulate, you can't do it in the superclass, and it is not logical to do it anyways. As was already mentioned, you can do something like this:
abstract class A {
public abstract void doStuff();
}
class B extends A {
static List<String>myArray = new LinkedList<String>();
public abstract void doStuff() {
// do B stuff
}
}
class C extends A {
static List<String>myArray = new LinkedList<String>();
public abstract void doStuff() {
// do C stuff
}
}
Static variable is bound to a class rather than an instance. If you need a separate static variable for subclasses, you need to declare them in each of your subclasses.
I have a abstract class where I want to declare final variables.
However, I want to assign the values to these variables only in the constructors of my sub-classes.
Apparently, this is not possible because all "final fields have to be initialized". I do not see why, since it is not possible anyway to instantiate an abstract class.
What I would like to have is something like this:
abstract class BaseClass {
protected final int a;
}
class SubClass extends BaseClass {
public SubClass() {
a = 6;
}
}
I imagine something similar to methods when you implement an interface. Then you are also forced to to implement the methods in the (sub-)class.
You should define a constructor in your abstract class that takes a value for a and call this constructor from your sub classes. This way, you would ensure that your final attribute is always initialized.
abstract class BaseClass {
protected final int a;
protected BaseClass(int a)
{
this.a = a;
}
}
class SubClass extends BaseClass {
public SubClass() {
super(6);
}
}
Can an abstract class have a final method in Java?
Sure. Take a look at the Template method pattern for an example.
abstract class Game
{
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
Classes that extend Game would still need to implement all abstract methods, but they'd be unable to extend playOneGame because it is declared final.
An abstract class can also have methods that are neither abstract nor final, just regular methods. These methods must be implemented in the abstract class, but it's up to the implementer to decide whether extending classes need to override them or not.
Yes, it can. But the final method cannot be abstract itself (other non-final methods in the same class can be).
Yes, there may be "final" methods in "abstract" class.
But, any "abstract" method in the class can't be declared final.
It will give "illegal combination of modifiers: abstract and final" error.
public abstract final void show();
illegal combination of modifiers: abstract and final
Here is the working example of the implementation.
abstract class Sian //ABSTRACT CLASS
{
public final void show() // FINAL METHOD
{
System.out.println("Yes");
}
public void display()
{
System.out.println("Overriding");
}
public abstract void success();
}
class Ideone extends Sian //INHERTING ABSTRACT CLASS
{
public void display()
{
System.out.println("Overridden");
}
public void success() //OVERRIDING THE ABSTRACT METHOD
{
System.out.println("Success overriding");
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone id = new Ideone(); //OBJECT OF SUBCLASS
id.show(); //CALLING FINAL METHOD
id.display(); //OVERRIDDEN METHODS
id.success();
}
}
OUTPUT:-
Yes
Overridden
Success overriding
Here is the ideone link:- http://ideone.com/G1UBR5
Yes.
Hint: just fire up your favorite IDE (eclipse, netbeans, etc) and try it out. It will complain if it does not work.
Yes.
Yes, those methods cannot be overriden in subclasses. An example of that is the template method pattern...
Yes it can ... need more characters
Of course, it means you can subclass it, but you cannot override that particular method.
Yes. The abstract modifier makes it possible to omit some of the implementation of a class (i.e. have some abstract methods) but does not impose any restrictions on you.
In Abstract Class methods may be defined or not. If we extend the abstract class then only it has meaning, so what ever methods we declare or defined in Abstract call it will over ride in subclass. So we can declare a method as final in Abstract class, and it will be over ridden in subclass.
Suppose I want to designed class which has some implementation but I do not want others(sub classes) to implement it but other methods, then in that case we need a final implemented method and obvious choice abstract class.
Yes, We can write the final method with implementation.
public abstract class AbstractWithfinalMethod {
public static final boolean m1() {
System.out.println(" M1 method executed");
return true;
}
public static void main(String[] args) {
System.out.println(m1());
}
}
output:
M1 method executed
true