Declaring an Interface and implementing in classes in an abstract class Java - java

I am doing an exercise, the book is not helping me grasp the concept, neither are the online resources. This may seem really silly but I don't know what I'm missing!!! I am quite new to Java and have had a look at other examples on stack but to no avail :s I need to declare 3 interfaces. Each interface needs to declare a method with the same name as its interface. Then the abstract class is extended by 3 classes which implement the aforementioned interfaces.Each class needs to be instantiated. If anyone could explain the procedure to this I would be eternally grateful.
interface antiLockBrakes{
public void antiLockBrakes();
}
interface cruiseControl{
public void cruiseControl();
}
interface powerSteering{
public void powerSteering();
}
public abstract class Auto{
abstract class Model1 extends Auto implements antiLockBrakes{
public abstract void antiLockBrakes();
Model1 mod1 = new Model1();
mod1.antiLockBrakes();
}
public static void main(String[] args){
}
}

this is your question: someone to explain how exactly to declare and interface and then have it implemented in the abstract class right??
Here's the answer for it.
See lets consider I have an interface
interface someInterface{
public void someMethod();
}
Now to implement the someInterface in abstract class
public abstract class SomeClass implements someInterface{
public void someMethod(){
System.out.println("Inside someMethod");
}
public abstract myMethod();
}
See in the class SomeClass we have implemented interface by giving definition to method someMethod() and since we want this SomeClass to be a abstract class we have defined one abstract method myMethod() for it.
Now any class which extends from SomeClass will also implement interface someInterface implicitly (because SomeClass has implemented it) and if it want its own definition for someMethod() it can override it. But if a child class wants to be a concrete class ( a class in which all its method will have implementation) then it has to provide implementation for abstract method myMethod().
HTH:)

this is what I like to use to see the difference between abstract classes and interface classes
interface class
//I say all motor vehicles should look like that :
interface MotorVehicle {
void run();
int getFuel();
}
// my team mate complies and write vehicle looking that way
class Car implements MotorVehicle {
int fuel;
public void run() {
System.out.println("Wrroooooooom");
}
public int getFuel() {
return this.fuel;
}
}
abstract class
// I say all motor vehicles should look like that :
abstract class MotorVehicle2 {
int fuel;
// they ALL have fuel, so why let others implement that ?
// let's make it for everybody
int getFuel() {
return this.fuel;
}
// that can be very different, force them to provide their
// implementation
abstract void run();
}
// my team mate complies and write vehicle looking that way
class Car2 extends MotorVehicle2 {
void run() {
System.out.println("Wrroooooooom");
}
}

Related

method implemented in abstract class, but appears in interface

I'm learning abstract classes vs interfaces at the moment and trying to figure out situations where to use one over the other. I'm having trouble figuring out this example at the moment:
public interface Face {
public void test();
}
public abstract class Tract {
public void test() {
System.out.println("over here");
}
}
public class Thing extends Tract implements Face {
public void test() {
// what should print out?
}
}
Here, the test() function is implemented in the abstract class. If you don't implement it in the subclass, would it call the abstract class' method and print out "over here"? Does the interface accept implementations from an ancestor class or do you have to implement it in the subclass, therefore overriding the abstract class implementation?
All the interface cares about is that the class has implemented a method called test() that returns void. It does not matter whether the method is implemented in the class directly or in any ancestor (parent) class.
In your case, the Thing class has inherited its definition of test() from Tract, and therefore implements the Face interface without you having to provide a definition explicitly.
In the class "Tract" you have given an implementation for the method coming from the interface. Also you override it in "Thing" class so when calling this method on a Thing instance then this version(Thing version) is going to be called.
All java methods are virtual.
lets consider little bit modified code,
I hope, you will get the idea:
public interface Face {
public void test();
}
public abstract class Tract {
public void test() {
System.out.println("Tract here");
}
}
public class Thing extends Tract implements Face {
public void test() {
System.out.println("Thing here");
}
}
public class Thing2 extends Tract implements Face {
}
lets go to output:
Tract tr = new Tract();
tr.test();
will not compile because you can't instantiate abstract class.
Thing th = new Thing();
th.test();
will print "Thing here"
Thing2 th2 = new Thing2();
th2.test();
will print "Tract here",
because you not overwritten the test() method in abstract class.
Main idea of this approach - you can abstract implementation in the future use
class C {
void print(Face face) {
face.test();
}
}
new C(new Thing()).print();
will print "Thing here";
new C(new Thing2()).print();
will print "Tract here";
You can hide different implementations
But this is not main idea of abstract classes.
main idea abstract classes are:
public interface Face {
public void test();
}
public abstract class Abstract {
abstract public void test();
}
public class Thing1 extends Abstract implements Face {
public void test() {
System.out.println("Thing1 here");
}
}
public class Thing2 extends Abstract implements Face {
public void test() {
System.out.println("Thing2 here");
}
}
main idea - you can declare method without implementation
new C(new Thing1()).print();
will print "Thing1 here";
new C(new Thing2()).print();
will print "Thing2 here";
main idea - you declare the method in abstract class, that you MUST override to compile code.
I hope, this is enough explained answer.

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

difference between instantiation an interface or implementing an interface

what is the difference between creating an Object of interface and implementing an interface
example :
public interface A{
public void testMethod();
}
on way is creating an object of interface
public class B{
A a = new A(){
#override
public void testMethod(){ //implemtation here }
};
}
other way is
public class B implements A
{
#override
public void testMethod(){}
}
You are wrong:
here you anonymously implement interface and you alrady have instance of annonymouse class
public class B{
A a = new A(){
#override
public void testMethod(){ //implemtation here }
};
}
Here you create named implementation, you only create class without instantiate it.
public class B implements A
{
#override
public void testMethod(){}
}
You can't create an object of interface. Interface it's an abstract class but with all the methods are abstract. In the first code you are creating an anonymous class (i recommend you to read about this feature in java) that implements the interface A, in this case you are limited with the interface's methods even if you define additional method in your implementation you can't call it. In the second code you are creating a class that implements the interface A which means that you have a class that at least contain all the methods defined in the interface A and you can add inside your class B other methods and call its.

Enforcing instance variable implementation from an abstract class in Java

I am trying to design an abstract class which will enforce implementation of an instance variable even though the type if this instance variable is unknown at the abstract level. For example:
public abstract class AbstractDiet{
abstract void computeMeat()
abstract void computeVeggies()
…
}
public abstract class AbstractAnimal{
protected AbstractDiet diet;
…
}
Then I'd like users to implement something like:
public class Cat extends AbstractAnimal{
protected CatFoodDiet diet; // CatFoodDiet extends AbstractDiet
…
}
Is this the best way to implement the diet variable? I want to ENFORCE that a subclass of AbstractDiet is always implemented in a subclass of AbstractAnimal.
First of all: Keep your instance variables private, and provide accessor methods.
Second of all: It sounds like you are trying to define an interface. Use an interface any time you want to say something like, "every animal has a diet."
interface Animal {
Diet getDiet();
...
}
If you like, you can also incorporate Bohemian's idea, and make it generic.
interface Animal<D extends Diet> {
D getDiet();
...
}
That way, you will have maximum freedom when it comes time to define different kinds of animal
class Cat implements Animal<CatDiet> {
CatDiet getDiet() { return...; }
}
You can't (and shouldn't) approach the design like that. Using abstract classes, try something like this:
public abstract class AbstractDiet {
abstract void compute();
}
public abstract class AbstractAnimal<T extends AbstractDiet> {
protected T diet;
}
public class CatFoodDiet extends AbstractDiet {
compute() {
//
}
}
public class Cat extends AbstractAnimal<CatFoodDiet> {
// use field in super which is type CatFoodDiet
}
But typically you would use interfaces instead of abstract classes for the abstract types.
The most flexible way is to just require the subclass to provide the information:
public abstract class AbstractAnimal {
// Subclasses must provide a function that returns the diet
public abstract AbstractDiet getDiet();
}
public class PetRock extends AbstractAnimal {
#Override
public AbstractDiet getDiet() {
return new SunlightDiet();
}
}
If you want to force a particular implementation, this is a common way:
public abstract class AbstractAnimal {
private AbstractDiet diet;
// Provide a constructor that sets a diet
protected AbstractAnimal(AbstractDiet aDiet) {
if (null == aDiet)
throw new NullPointerException("Diet must be specified");
diet = aDiet;
}
public class PetRock extends AbstractAnimal {
public PetRock() {
// Subclasses have to provide a diet to the superclass
super(new SunlightDiet());
}
}

concrete class method keeps throwing an exception from abstract class despite implementation

I have an abstract class Automobile which has an unimplemented method called move
so
public abstract class Automobile {
public void move() {
throw new UnsupportedOperationException();
}
}
I have a concrete class which extends my abstract class and implements the move method.My problem is the method keeps throwing an UnsupportedOperationException
public class Car extends Automobile{
int x;
public void move(){
x++;
}
}
It could be for many reasons in your concrete class: maybe your concrete doesn't actually extends Foo? Or maybe it calls super.move() somewhere in its body.
Instead of throwing an exception, the correct way is to define the class and method as abstract to force subclasses to override it.
public abstract class Foo {
public abstract void move();
}
Please note if Foo only has abstract methods, like in the example above, that's an interface that you want, not an abstract class. Also, you should name it to define a behaviour
public interface Moving {
void move();
}
And then:
public class MovingObject implements Moving {
....
#Override
public void move() {
// your implementation
}
....
}
Are you calling super.move() in your implementation class? Eclipse generates that call by default if you used Source->Override/Implement Methods...
Otherwise I think, that you did not override the method correctly.

Categories