Can an abstract class have a final method? - java

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

Related

Share a variable between functions in implementation of a interface

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

Is forcing a constructor signature a valid reason to use an abstract class rather than an interface?

For a project, I have written the following interface:
public interface IManipulation {
void applyManipulation (double value);
}
Since I would like to force all implementing classes to use a certain constructor signature, I have been considering to change the interface into something like the following abstract class:
(edit: I forgot that it's not possible to have an abstract constructor, so I changed the "solution" below a bit)
public abstract class Manipulation {
private Signal signal;
public Manipulation (Signal signal) {
this.signal = signal;
}
public abstract void applyManipulation (double value);
protected Signal getSignal () {
return signal;
}
}
The reason for wanting to force this constructor is because every implentation should have an instance of Signal available. (and it should not be possible to reassign this signal)
Is this a valid reason to replace the interface with an abstract class (and live with the limitations that come with it), or are there any other potential solutions?
instead of an abstract class you should use an init method for that purpose.
public interface MyInterface{
public void init(YourParam p);
//... other methods
}
in the init you check, if the class is allready initialised if yes, just return.
So you have still an interface and can extend from other classes.
Instead of the constructor you will call the init method for your initialization
EDIT:
public interface IManipulation {
void init(Signal s);
void applyManipulation (double value);
}
You should use abstract classes only, if you have implementation details in it, which are shared by all subclasses. For Method signatures use interfaces
You can make empty constructor private in the abstract class:
abstract class AbstractManipulation {
private final Integer signal;
private AbstractManipulation() {
signal = null;
}
public AbstractManipulation (Integer signal) {
this.signal = signal;
}
}
class Manipulation extends AbstractManipulation {
public Manipulation(Integer signal) {
super(signal);
}
// Cannot redeclare
//public Manipulation() {
//}
}
Then:
public static void main(String[] args) {
// Will not work
//Manipulation m = new Manipulation();
// This one will
Manipulation m = new Manipulation(1);
}
You should not choose for technical reasons but rather logical, ie an abstract class is used when you have a realtion with the sub-classes like for example person: student, teacher. An interface is used when you want to impose a service contract for classes that may not have a relationship between them.

Can we create instantiation of interface and abstract class with the help of anonymous class in Java?

I went to an interview. Interviewer asked me if one can instantiate an interface and abstract class? As per my knowledge I said "No". But he said "Yes, we can with the help of an anonymous class".
Can you please explain to me how?
This was a trick questions.
No you can not instantiate an interface or abstract class.
But you can instantiate an anonymous class that implements/extends the interface or abstract class without defining a class object. But it is just a shortcut to defining a fully named class.
So I would say technically your answer was correct.
I don't know what is "instantiation of interface and abstract class".
I think it's an inaccurate, improper expression of something,
we can only guess at the intended meaning.
You cannot create an instance of an interface or an abstract class in Java.
But you can create anonymous classes that implement an interface or an abstract class.
These won't be instances of the interface or the abstract class.
They will be instance of the anonymous class.
Here's an example iterator from the Iterator interface that gives you an infinity of "not really":
new Iterator<String>() {
#Override
public boolean hasNext() {
return true;
}
#Override
public String next() {
return "not really";
}
};
Or a funky AbstractList that contains 5 "not really":
List<String> list = new AbstractList<String>() {
#Override
public int size() {
return 5;
}
#Override
public String get(int index) {
return "yes";
}
};
Assume you have an abstract class: MyAbstractClass with abstract void method myAbstractMethod. Then you can make an "instance" of this class via this code:
MyAbstractClass myAbstractClassInstance = new MyAbstractClass() {
public void myAbstractMethod() {
// add abstract method implementation here
}
};
myAbstractClassInstance extends your MyAbstractClass in this case. When you instantiate this class you have to implement all abstract methods as you can see from the code above.
The same way works for interfaces, assume you have an interface MyInterface with a void method myInterfaceMethod inside, then you can create an "instance" (implementation of this instance) via this code:
MyInterface myInterfaceImpl = new MyInterface() {
public void myInterfaceMethod() {
// add method implementation here
}
}
myInterfaceImpl is an implemetation of MyInterface in this case. When you create an object using interface, you have to implement interface methods as it is shown above.
Interface :
interface Interface1 {
public void m1();
}
When you right
new Interface1() {
public void m1() {
}
}
Its not actually creating the instance of Interface. Its creating an instance of its subtype which doesnt have any name/reference. Hence we cannot create an instance of interface or abstract class
You cannot create instances of abstract classes or interfaces using the new operator. For example,
new AbstractSet(); // That's wrong.
You can, however, use them to declare reference variables. For example, You can do this:
AbstractSet set;
You can instantiate anonymous as well as declared implementing classes or subclass.
For example, Set extends AbstractSet, so you can instantiate Set.
Yes, we can create by having defining the abstract methods or the interface methods on the fly during instantiation. That's like a Named anonymous class.
//interface
Runnable r = new Runnable(){
public void run() {
System.out.println("Here we go");
}
};
//Abstract class
abstract class MyAbstract {
abstract void run();
}
MyAbstract ab = new MyAbstract(){
#Override
void run() {
System.out.println("Here we go");
}};

Can a variable be abstract in an abstract Java class?

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();
}
}

Overriding Protected Methods

I'm new to Java and I have a very basic question.
I have 2 Parent Class under the same package. Animal Abstract Class and the Machine Class.
Now, the Animal Abstract Class has a protected method. I'm aware that protected methods are accessible if the classes are under the same package.
I can access that protected method in my Machine Class, and the question is.. Is it possible to override that protected method? Without extending the Animal Class.
protected - Can be overridden by subclasses, whether they are in the same package or not
default (no access modifier) - can only be accessed or overridden if both the classes are in the same package
You can only override methods through extension.
You can override a protected method with an anonymous subclass, if you like. E.g.
public class Animal {
protected String getSound() {
return "(Silence)";
}
public void speak() {
System.out.println(getSound());
}
}
In another class:
public static void main(String ... args) {
Animal dog = new Animal() {
#Override
protected String getSound() {
return "Woof!";
}
}
dog.speak();
}
Will output:
Woof!
No , Overriding means inherit the behavior from parent class and that is not possible without extending the class.
public class PClass
{
protected boolean methodA()
{
return true;
}
}
public class CClass extends PClass
{
protected boolean methodA()
{
return false;
}
}
Run the code below to test it
public static void main(String[] args)
{
PClass pc = new CClass();
System.out.println(pc.methodA());
}
O/p=false
here we are overriding the behavior of methodA
In order to override a method you have to extend that class. That's what overriding means: having a method with the same signature as the super-class.
Overriding by definition says..
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
So AFAIK if you don't extend the super class there is no way to override the method.

Categories