Referencing a variable declared in abstract class from inherited class - java

I'm currently reading a book on design patterns which is written towards java, but would like to code examples in both Java and C#. Right now I'm trying to implement the strategy pattern in C#, and while I've found a lot of examples online, my current problem is something that I want to figure out the most.
In the Java example I have an abstract class and then a class that extends that abstract class. In the abstract class I declare, but don't instantiate, variables of an interface, which are then instantiated in the extended class.
Interface:
public interface MathStuff{
public void add();
}
Abstract:
public abstract class Math{
MathStuff mathStuff;
public Math(){}
public void addStuff(){
mathStuff.add();
}
}
Extended Class:
public class DoStuffWithMath extends Math{
public DoStuffWithMath(){
mathStuff = new RandomClass();
}
}
Now I would really like to replicate this in C#. The C# code is essentially the same. I have an interface, an abstract class, and a class that I assume is extending the abstract class. I am not as familiar with C#. That class looks like this.
class DoStuffWithMath : Math{
public DoStuffWithMath(){
mathStuff = new RandomClass();
}
}
The problem with the C# code is where i try to say "mathStuff = new RandomClass()". Any help or reading material would be appreciate.

Explicitly adding protected would fix the issue (to override default private access):
public abstract class Math{
protected MathStuff mathStuff;
public Math(){}
public void addStuff(){
mathStuff.add();
}
}
Note that depending on your needs either passing mathStuff as constructor of base class or using property instead of field would be better solution.

Related

Class of unknown type with an upper bound

Suppose i have an interface and two extending classes, like below;
public interface UpdateHelper<T>{
List<T> getItemsToOperate();
}
public class ProfileUpdateHelper implements UpdateHelper<Profile>{
//class logic
}
public class PlayerUpdateHelper implements UpdateHelper<Player>{
//class logic
}
Player and Profile are two concrete classes. When i design my classes like above everything is fine. But i would like to introduce another abstraction layer between concrete Profile and Player classes such as;
public abstract class Updatable{
//common attributes will be here
}
public class Player extends Updatable{
}
public class Profile extends Updatable{
}
And use my helper classes like that;
public interface UpdateHelper<T>{
List<T> getItemsToOperate();
}
public class ItemUpdateHelper<? extends Updatable> implements UpdateHelper<Updatable>{
//class logic
}
I think I should use wildcards since any class instance extending updatable can be used with helper classes and it should not matter which sub-class instance is being used.
But when i write like above i get an unexpected wildcard error just after class names and code won't get compiled. Am i missing something, doing something wrong or something like that can't be done in java. By the way I am using java 8.
You can't use wildcards in class declaration. Instead, you pass a type parameter like T:
public class ItemUpdateHelper<T extends Updatable> implements UpdateHelper<Updatable>{
...
}
You can specify concrete implementation of Updatable:
ItemUpdateHelper<Player> playerHelper = new ItemUpdateHelper<>();
ItemUpdateHelper<Profile> profileHelper = new ItemUpdateHelper<>();
or not:
ItemUpdateHelper helper = new ItemUpdateHelper();
You would want to implement it like,
public class ItemUpdateHelper<T extends Updatable> implements UpdateHelper<T>{
}

What use cases remain for abstract classes as of Java 8?

Given the provision of default and static methods new possibilities in interfaces, could someone help with use cases that might still warrant me to want to use Abstract Classes for inheritance hierarchy of common behaviors?
Normally, I would have:
public interface Shape
{
void draw();
}
With a hierarchy class like so:
public abstract class Triangle implements Shape
{
public void sayMyCategory(String name)
{
System.out.println(name);
}
}
And then have:
public class RightAngleTriangle extends Triangle
{
public void draw()
{
System.out.println("Right Angle Triangle Drawn");
}
}
With Java 8, I only need to have:
public interface ShapeImpr
{
void draw();
public default void sayMyCategory(String name)
{
System.out.println(name);
}
}
And then:
public class RightAngleTriangleImprv implements ShapeImpr
{
public void draw()
{
System.out.println("Right Angle Triangle Drawn");
}
}
Abstract class can define non-public methods, which is obviously not possible in interface.
There is a reduced need for abstract classes as some things that previously you needed them for can now be done by interfaces.
However abstract classes still can do things that interfaces cannot. For example containing member variables.
A simple example would be an interface that specifies listeners (addListener, removeListener, notifyListeners). The interface cannot provide a default implementation of those methods, however you can provide an abstract class which does.
You can also define things like protected methods in an abstract class which the people using the abstract class have to implement but which are not published as part of the public API.
The new features of java 8 are there to enable some behaviours we previously used interfaces for. Abstract classes are a structural concept. You use them to implement the IS-A relationship between classes in a class hierarchy.

Implementing interface with just one class or more classes

Maybe its answer is obvious for most of you but I am a bit confused when implementing an interface.
Should “just one implementation class” implement “the complete set of methods”?
Forex:
public class CCSImplementation implements CCS {
public void addComment (int submissionId,int customerId, String comment, Date date) { }
public void addGeneralComplaint (int submissionId, int customerId, String description, Date date) { }
and other methods…..}
Or
- More implementation classes such as
public class Comment implements CCS {
public void addComment() {}
}
and
public class GeneralComplaints implements CCS {
public void addGeneralComplaint(){}
}
implement the interface part by part taking into account of related methods? (---I got error when implement like these)
Since a reference says
One or more classes can implement that interface...
as I said I am a bit confused.
If the class is abstract, you don't have to implement all/any of the methods:
public abstract class Comment implements CCS {
public void addComment() {}
// addGeneralComplaint() is implied as abstract
}
Depending on your need, it would be perfectly valid to define such a class, where some of the methods are implemented, but subclasses are left to implement the rest of the interface's methods.
When a non-abstract class implements an interface it must provide implementations of all the exposed by the interface methods.
If we have an abstract class A, it can implement an interface without providing method implementations of the interface-exposed methods, since all of them are abstract by default. But when this class is subclassed by a non-abstract class B, the subclass must provide the implementations of the interface-exposed method signatures.
class Comment should extends Class GeneralComplaints
or
class GeneralComplaints should extends class Comment..
If it turns out that you are using an abstract class then you don't have to use everything. From my understanding you only want to implement something if you plan on using the provided methods. It was explained to me that an interface s provided so that the user doesn't forget to use methods in their class. Hope this helps.

Abstract class with all methods abstract - Practical Example

I am asking a very basic question and it may be marked duplicate (I could not find the answer though):
Is there any practical example of an Abstract Class with all the
methods declared as Abstract?
In most cases and as mentioned in Java Tutorial also, class with all methods abstract shall be an interface.
But since abstract class and interface are two different concepts, I am looking for an example compelling to have "complete abstract class"
The only practical approach i think is that Abstract class can hold state. So you can have inside properties with access level protected, and you can make protected abstract methods that in interface you can't cause all are public.
A practical example could be for example this, the protected method in java has 'inheritance access' and 'package access'.
public interface Operation{
void operate();
}
public abstract class AbstractClase implements Operation{
protected Operation delegate;
public AbstractClase(Operation delegate){
this.delegate=delegate;
}
//delegate implementation responsability to children
protected abstract doSomething();
}
The downside of using abstract class is that you loss the possibility to extends of something else too.
As well as for holding state, it's worth remembering that all interface members are implicitly public. So restricting visibility of abstract methods may itself be a compelling enough reason to use an abstract class instead of an interface.
Adding to the two answers given above, Interfaces can only have constants(Variables which are public,static and final) while there is no such restrictions for abstract classes.
Abstract classes can have constructors which will be implicitly called when a child class is instantiated (if it is non-parameterised). But this is not possible with interfaces.
Here is an example for the usage of an abstract class
abstract class Animal{
public int noOfLegs;
public boolean isAlive;
Animal(){
isAlive = true;
}
public abstract void walk();
}
class Cow extends Animal{
Cow(){
noOfLegs = 4;
}
public void walk(){
if(isAlive){
//Code for walking
}
}
}
One other general purpose of an abstract class is to prevent an instance of the class., for example
abstract class Mammal{
int i=0;
}
public class Man extends Mammal{
public setMeValue(int i){
this.i=i;
}
public static void main(String args[]){
Mammal m= new Man();
man.setMeValue(10);
}
}
In the above code, I effectively make sure that there will never be an object of instance Mammal.
An interface can be applied to wildly different classes. Classes that have no relation to each other are Serializable or Cloneable. However, subclasses of an abstract class are all related. This may not mean anything when implementing the interface or extending the abstract class, but it means something semantically.
There is a style of programming where all the methods of a base class are either public final, protected abstract, protected and empty, or private. But even that isn't what the OP was interested in.
Adding more to the below answers:
Interface provide you with a contract to implement where abstract Class may provide you with a template as well. For a simple scenario you can use an Interface or an abstract Class without thinking much. But having an abstract class just for maintaining a state might give you lot of problems in a complex implementation. In such cases you have to carefully consider what you really want to achieve in your code and make the decision. If you consider the case of maintaining the state in your code, you can always use the State pattern in your implementation, so you will be able to use an interface in your code. You should always consider the extend-ability and maintainability of your code before deciding to use an abstract class over interface.
The simplest practical example I can think of is a class that has a protected variable:
public abstract class RoadVehicle {
protected int numberOfTires;
protected String vinNumber;
protected VehicleRegistration registration;
public abstract void drive();
public abstract double calculateToll();
public abstract void changeTires();
// so on and so forth...
}
You can't do this with an interface.
public abstract class animal{
public abstract void speak(){
System.out.println("animal voice");
}
}
public class dog extends animal{
public void speak(){
System.out.println("dog voice");
}
}
The biggest motive behind having Pure Abstract classes is to allow future extension. Assume you have an Abstract class (with all abstract members), then you inherit that abstract class in 20 derived classes. Sometime in future you wish to add a public method to 5 of your derived classes, what do you do ?
Since you already inherit the abstract class, an easier solution is to add the method (with implementation) to the abstract class. This way you don't have to touch any of the derived classes. Interfaces are very rigid in this context, once created there is very little chance to change an Interface, as it would require changing all the classes that implement that Interface.

How to call abstract class methods to another class in java

can anybody tell me that. how can I call abstract class method to my own class in java?
thanks in advance
First of all look at you abstract class, it shall contain abstract methods and real methods. In the following sample the Foo class has an abstract method (FooMethod) and a real method (Yeee).
public abstract class Foo {
public abstract int FooMethod(int i);
public int Yeeee() {
for (int i = 0; i < 3; i++) {
int res = FooMethod(i);
// Do whatever
}
}
}
Abstract class are not meant to be directly used, so we have to inherit from them with a concrete class. The following inherits from the abstract (implementing the abstract method)
public class Bar extends Foo {
public int FooMethod(int i) {
// do something with i
}
public static void main (string [] args) {
Bar obj = new Bar();
obj.Yeeee();
}
}
Note: when in the main you call obj.Yeee() the base class method gets invoked, but in place of the abstract FooMethod, your own new implementation is used.
This is just the tip of the iceberg with abstract classes, but roughly should point you to the right direction.
Please take a good read here is a good tutorial and should give you some initial wisdom about inheritance and abstract classes.
You need to first create a subclass of the abstract class. This will then contain the methods of that abstract class. You use the "extends" keyword.
For example:
public class MyClass extends AbstractClass
{
//class content here...
}
For methods in abstract classes you need not to create the instance of the abstract class
So after importing the package in which the abstract class is present you can just call the method as below
YourAbstractClassName.methodName(args if any);
since abstract classes cant be instanciated in Java, You cant have member functions in this class and if you want to have one than their is a logical problem. However if you want to call the static methods, you can simply call them using class name, i.e.
YourClassName.fuctionName(parameters if any);
Do you mean how to implement that method in your class ?
if that is what you want to understand
then you just have to extend your class with the abstract one
for example
abstract class GraphicObject {....}
class Circle extends GraphicObject { ... }
try http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can call the method in abstract class by creating an
object of subclasss of the abstract class
or
if u want to call from the abstract class then you have to make your method static then you can call from main method like
Abstract_className.methodName()

Categories