I have a sub class that extends abstract class called AbstractParentClass
like
class Child extends AbstractParentClass
This AbstractParentClass contains a method called getParentAbstractServiceMethod which returns some service class object. That services class has another method called getParentAbstractClassDomainFacade which returns some other class object which is not abstract and so on...This is like method chaining.
Snippet inside Child class is as follows
SessionClass userSession = (SessionClass)
getParentAbstractServiceMethod().getParentAbstractClassDomainFacade().getParentAbstractClassDomainObject(SessionClass.NAME);
How to mock getParentAbstractServiceMethod() method since this is abstract class method I cannot instantiate it and call..
The best solution was to follow the "Favour composition over Inheritance" principle and turn the AbstractServiceClass into a regular class that gets the current extenders as dependencies implementing an interface that provides the method to be called on them.
having written this the less advisable solution is to create a mock of the Abstract class using Mockito:
AbstractParentClass cut= Mockito.mock(AbstractParentClass.class,Mockito.CALLS_REAL_METHODS);
Mockito.when(cut.getParentAbstractServiceMethod()).thenAnswer(...);
I think you should step back and look at your design. What is the point of testing a child class (of an abstract class) ... that doesn't implement the abstract methods in the first place.
I think you should do the following:
A) test your base class as far as possible; for example by creating a test only child class that somehow meaningfully implements the abstract methods
B) make sure that your "real" child classes provide reasonable implementations of your abstract methods.
And hint: consider not putting abstract into your method names. They are only abstract on the parent level; not in the childs that implement them.
Related
In context of Java, could a class replace the need of extending an abstract class by extending another non-abstract class and implementing an interface together, both of which combined have all the methods(abstract and implemented), of an abstract class?
In context of Java, could a class replace the need of extending an
abstract class by extending another non-abstract class and
implementing an interface together, both of which combined have all
the methods(abstract and implemented), of an abstract class?
Can it? Yes
Should it? No
An abstract class can be replaced by a concrete one, but you will be altering your system.
Do remember: an abstract class can not be instantiated, nor should it be, since it's not 'concrete enough' to make sense for your business. (If it does, it shouldn't have been an abstract class to begin with)
If you make it concrete, you risk that developers will use instances of the (what-should-be) abstract class.
If you change it the way you propose:
public void doSomething(MyAbstractClass instance){
// here we know there is an implementation provided by a subclass
}
would become
public void doSomething(MyShouldBeAbstractClass instance){
// here they can pass instances of the base class, which might have unsupported methods
}
For instance:
public String getConcreteInformation(){
throw new UnsupportedOperationException("Should be called on a child class");
}
and could lead to a lot of nasty bugs
I want to extend a class A and call the constructor of the class A from the child class B with the super() method. Also should the class A only be instantiated via the child class B. I can do that very simply by making class A abstract. But I read that I should only declare classes abstract, when they have at least one abstract method. Is there another way of making class A only be instantiated by the child class B by calling the super() method?
You should use abstract if there are certain implementations your child class needs, especially if you don't want the parent class to be instantiated ever!
However, in your case, I don't think there are any methods that need to be implemented or inherited, so you can just use protected.
Good luck!
I am now studying a java and I'm at the part of Abstract.
I read sorta strange part to me that there is an abstract class
which does not include any abstarct method.
Why do they use this kind of class?
To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.
A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.
Yes, we can have abstract class without any abstract method.
Best example of abstract class without any abstract method is HttpServlet
If this class extends another abstract class and don't have implementation of inherited abstract methods.
This class contains some common logic for all its inheritors, but itself does not represent usable entity (in terms of particular application)
These type of classes are used for a implement a general logic which can be implemented by other classes. Making it abstract prevents from instantiating it. But other classes can inherit the class and its methods.
Say you have a set of related classes, but no related (shared) code, yet. If we make all of these classes extend a base class with no abstract methods, that then if we wan't all of these classes to have an identical method/feature in the future, that can be done in one shot by putting it in the base class. So code is not repeated and it reflects in all child classes by including it in just one place.
Another example for having such class is when you implement creation helpers. These classes are used to ease the client in the creation of objects, which are related in topic but decoupled depending on the need. By nature, the methods of this creator classes are all static and they can be seen as utility classes as well.Obviously, instatntation of this classes is futile and hence the abstractkeyword.
To mention a recent example I met was the Sftpclass from org.springframework.integration.dsl.sftp which is basically an easy way to require objects (e.g: adapters, gateways) from the sftp api.
I develop a abstract class to prevent instantiation of that class and use it only as a base class. because, These type of classes are used for a implement a general logic which can be implemented by other classes. Sometimes, I have a default implementation for every method in abstract class. In the manner, it doesn't force the sub-class to override all of method, but also it implement everyone that is need.It means implicitly you have to override at least one method to make scene using this abstract class.
I can't think of any good reason to use it. It could be used as "marker" but an interface would be a better choice.
Abstract class without abstract method means you can create object of that abstract class.
See my Example.
abstract class Example{
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo
{
public static void main(String[] args)
{
Example ob = new Example(){};
ob.display();
}
}
If you write one abstract method inside abstract class then it will not compile.
Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.
Is it possible that different child classes have different visibilities to the methods of the parent. Suppose there is a class A which has 10 methods defined. It has two different child ClassB and ClassC. Is it possible that that ClassB and ClassC has access to different methods of ClassA. Like ClassB has access to only 6 of 10 methods defined in ClassA and ClassC has acess only to the other 4 methods of ClassA? ClassB and ClassC are in same package.
Thanks,
Asit
I don't think it is possible with classes. To segregate functionality you should use interfaces instead of extending classes.
It is quite likely that your class A is violating the Single Responsibility Principal if you need to divide methods like that.
Then look to use composition instead of inheritance to compose complex classes from the simpler ones. Also take a look at the strategy pattern.
Divide your functionality in interfaces like this -
public interface IFlyable
{
void FlapWings();
void Fly();
}
public interface IHuntingAnimal
{
void Hunt();
}
Then implement your classes like this -
public class Duck : IFlyable { ...
public class Eagle : IFlyable, IHuntingAnimal { ...
public class Tiger : IHuntingAnimal { ..
Note: The example is in C#. You need to work out the java equivalent.
You can do such a thing with interfaces, but not concrete classes.
Adapter or Decorator pattern will help you.
From you wrote, i suppose what you have is
package first;
class A {
protected methodA() {...}
private methodB() {...}
public methodC() {...}
methodD() {...}
}
package second;
class B extends A {...}
class C extends A {...}
In this case, B and C will only see methods methodA and methodC from class A.
methodB is private, so unreachable
methodD is package protected, that's to say restricted to classes in same packgae (a weird way to have an equivalent of the C++ friend keyword, I realize now), and as a consequence not visible outside of packgae first.
not really understood what do you mean...
it is generally possible that methods of a parent class have different access modifiers as possible inherent classes. but with one condition (citation from lang spec):
The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs.
you cannot coarct usability of a class, i.e. if a method from your class A was "protected" then you can declare an overriding method in your class B as "public". but it doesn't work vice-versa
I don't know the context of your question so I can't comment as to whether your design is sound and by extension, whether your motivation for this is justified. Since others have already taken the stance that your ClassA requires refactoring, I'm going to do the opposite and assume that it's a sensible class with a single well-defined purpose and it doesn't require subdivision.
In which case, why not use the object adapter pattern to achieve what you're after? You can expose the ClassA methods you want to in your ClassB and ClassC adapters by implementing wrapper methods which forward invocations to your ClassA adaptee. And of course, you can optionally extend those methods.
This answer is predicated on your use of the term child class
Short answer no
Longer answer
In this situation:
class Base has the following methods: method1, method2, method3
There is no way, using Java, to setup the following situation:
class Derived1 (this class extends class Base) can access method1 and method2, but cannot access method3.
class Derived2 (this class extends class Base) can access method1, method2, and method3.
Both classes are in the same package.
In Java, when one class extends another class these things always apply:
The derived class may call every public method of the base class.
The derived class may call every protected method of the base class.
The derived class may not call any private method of the base class.
If the derived class is in the same package as the base class,
the derived class may call every package access method of the base class.
Can I define an abstract class without adding an abstract method?
Of course.
Declaring a class abstract only means that you don't allow it to be instantiated on its own.
Declaring a method abstract means that subclasses have to provide an implementation for that method.
The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final methods but never the other way around.
Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.
So you can easily define an abstract class without any abstract method.
As for Example :
public abstract class AbstractClass{
public String nonAbstractMethodOne(String param1,String param2){
String param = param1 + param2;
return param;
}
public static void nonAbstractMethodTwo(String param){
System.out.println("Value of param is "+param);
}
}
This is fine.
Yes you can do it. Why don't you just try doing that?
YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet
Abstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.
You cannot create objects of abstract class, which means that it cannot be instantiated.
Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
Yes, you can declare a class you cannot instantiate by itself with only methods that already have implementations. This would be useful if you wanted to add abstract methods in the future, or if you did not want the class to be directly instantiated even though it has no abstract properties.
yes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.
so two cases
1) abstract class with abstract methods.
these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class,
ex: GenricServlet class
2) abstract class without abstract methods.
these type of classes, we must inherit a class from this abstract class,
ex: HttpServlet class
purpose of doing is although you if you don't implement your logic in child class you can get the parent logic
please check the HttpServlet source code
You can, the question in my mind is more should you. Right from the beginning, I'll say that there is no hard and fast answer. Do the right thing for your current situation.
To me inheritance implies an 'is-a' relationship. Imagine a dog class, which can be extended by more specialized sub types (Alsatian, Poodle, etc). In this case making the dog class abstract may be the right thing to do since sub-types are dogs. Now let's imagine that dogs need a collar. In this case inheritance doesn't make sense: it's nonsense to have a 'is-a' relationship between dogs and collars. This is definitely a 'has-a' relationship, collar is a collaborating object. Making collar abstract just so that dogs can have one doesn't make sense.
I often find that abstract classes with no abstract methods are really expressing a 'has-a' relationship. In these cases I usually find that the code can be better factored without using inheritance. I also find that abstract classes with no abstract method are often a code smell and at the very least should lead to questions being raised in a code review.
Again, this is entirely subjective. There may well be situations when an abstract class with no abstract methods makes sense, it's entirely up to interpretation and justification. Make the best decision for whatever you're working on.
yes you can do that.
declaring class abstract means that class will not be instantiated by any other class.
and there should be at least one abstract method inside that and meaning of that you can declare abstract method in that class if you are not declaring method than its ok.
example:
public abstract class abs {
protected int cx = 0, cy = 0;
public void p() {
System.out.print("hello");
}
}
this will work for sure.
Yes you can. Sometimes you may get asked this question that what is the purpose doing this?
The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class
Actually there is no mean if an abstract class doesnt have any abstract method . An abstract class is like a father. This father have some properties and behaviors,when you as a child want to be a child of the father, father says the child(you)that must be this way, its our MOTO, and if you don`t want to do, you are not my child.
Yes, you can define an abstract class without an abstract method. However, if there is no method inside you might better go with an interface