write java interface - java

as I declare a table of strings in all java testss and functions , is it possible de declare it once in an interface and to call it anywhere ?
public interface string {
string[] mytab = new string[2];
}
in the java class :
public class Test { }
How can I call the inetrface to say :
if (mytab[1].equals("toto")){}

I guess this is what you are asking about. This should work for you.
public interface MyInterface {
static final String myString = "abc";
}
public class Test {
static void test() {
if (MyInterface.myString.equals("abc")) {
// ...
}
}
}

I believe you can define static objects in an interface.

Related

How to use variable of method from 1 class in 2 class via Java?

public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);

Creating multiple objects using the same instance

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();

Interface Segregation Principle

I'm learning SOLID principles with Java and I'm trying to implement two classes with this. My problem is about ISP. I have some methods that is present in one class but not in the other and I also have to refer both classes with the same interface.
This is the first class:
public final class Complex implements Number {
#Override
public String polarForm() {
//This class needs to implement this method
}
#Override
public String rectangularForm() {
//This class needs to implement this method
}
}
Here is the second one:
public final class Real implements Number {
#Override
public String polarForm() {
//This class does not need this method!
}
#Override
public String rectangularForm() {
//This class does not need this method!
}
}
Finally I have to refer to the classes something like this:
public static void main(String[] args) {
Number c = new Complex();
Number r = new Real();
Number n = c.add(r);
System.out.println(c.polarForm());
System.out.println(n);
}
How can I refer to both classes with the same interface without implementing unnecessary methods?
An alternate solution to approach this problem would be to use Composition instead of Inhertiance in conjunction to the interface segregation principle.
Number class
public class Number {
private RectangleForm rectangleForm;
private PolarForm polarForm;
private BigDecimal value;
public Number(RectangleForm rectangleForm, PolarForm polarForm,BigDecimal value) {
this.rectangleForm = rectangleForm;
this.polarForm = polarForm;
this.value = value;
}
public String polarForm() {
return polarForm.transform(this.value);
}
public String rectangleForm() {
return rectangleForm.transform(this.value);
}
//other methods such as add and subtract
}
PolarForm interface
public interface PolarForm {
public String transform(BigDecimal number);
}
RectangularForm interface
public interface RectangleForm {
public String transform(BigDecimal number);
}
RectangleForm implementation for real numbers
public class RectangleFormReal implements RectangleForm {
#Override
public String transform(BigDecimal number) {
String transformed = "";
//transfromed = logic to transform to rectangle form
return transformed;
}
}
PolarForm implementation for Real numbers
public class PolarFormReal implements PolarForm {
#Override
public String transform(BigDecimal number) {
//return the number as is without any transformation
return number.toString();
}
}
Putting the pieces together
public class NumberTest {
public static void main(String[] args) {
RectangleForm rf = new RectangleFormReal();
PolarForm pf = new PolarFormReal();
Number number = new Number(rf, pf,new BigDecimal(10));
String rectangleForm = number.rectangleForm();
String polarForm = number.polarForm();
}
}
You can create the PolarFormComplex and RectangleFormComplex implementations and wire theNumber instance in a similar fashion. The advantage of this approach is that your code will always rely on the interface of the Number class (by interface I mean the public APIs) and you can chose the transformation strategy by injecting the corresponding PolarForm or RectangleForm instances into your Number instance at compile time as shown above or at runtime (via a factory)
Break your Number interface (or base class) into multiple interfaces. The standard operations (add, subtract, etc) are in one; let's say INumber. polarForm and rectangularForm are part of another; let's say IComplex.
Real would implement INumber; Complex would implement INumber and Icomplex. You could then treat both as INumber.
If necessary, you could also create another interface that implements both.

Loop calling update() method of each class with different parameters

Say I have 3 different classes (Class1, Class2, Class3), and each class has a method called ".update(String x)".
Now I want to read a line in a .csv file, I separate the values by comma and get a list with each string value indexed , for example "Foo, bar, barz" becomes {"foo", "bar", "barz").
Is it possible in Java to make a list of objects (Obj1, Obj2, Obj3), one for each class and for each value on my list of strings, call the .update of each object with the according index of my list of strings as the parameter?
for example:
package Test;
import java.util.ArrayList;
import java.util.List;
class Class1{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
class Class2{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
class Class3{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
public class Testing {
public static void main(String[] args) {
List<Object> object = new ArrayList<Object>();
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Class3 class3 = new Class3();
object.add(class1);
object.add(class2);
object.add(class3);
String string_list[] = {"foo" , "bar", "barz"};
for(int i = 0 ; i < object.size(); i++) {
object.get(i).update(string_list[i]);
}
}
}
hence obj1.update("foo"), obj2.update("bar"), obj3.update("barz")
I keep getting a "cannot resolve method" error in the loop.
Error:(68, 26) java: cannot find symbol
symbol: method update(java.lang.String)
location: class java.lang.Object)
But when I change the object reference in the loop to an object and not a reference it works fine. Logically it seems correct, but it seems like an ArrayList list isn't the right data structure to hold objects? or maybe it is and I'm doing it wrong, anyone have any suggestions why it's not working and how I can fix it?
Thanks.
you can do that, but for that you need your list of objects to be of a type that declares the update() method. If you want the objects to be of different classes, you need to have some interface or abstract class that all three implement/extend, and that interface/abstract class should declare update method.
should be something like this:
public interface MyInterface {
public void update(String str);
}
public class Object1 implements MyInterface {
#Override
public void update(String str) {
...
}
}
/// same for object 2 and 3
String[] string_list = {"foo", "bar", "barz"}
MyInterface[] obj_list = {Obj1, Obj2, Obj3}
...
...

Adding new implementations safely

I have interface and its implementations:
public interface SyntaxConstruction{
public String parseFromString(String str);
}
public class Copy implements SyntaxConstruction{
public String parseFromString(String str){ //impl };
}
public class Set implements SyntaxConstruction{
public String parseFromString(String str){ //impl };
}
I also have the following class:
public class Parser{
private static List<SyntaxElement> elementPrototypes; //should maintain the list of all implementation's prototypes
static{
//Initializing list with prtotypes of all possible SyntaxConstruction's implementations
}
public static List<SyntaxElement> parse(String str){
//getting syntax elements from str
}
}
Now we add a new implementation, say
public class Values implements SyntaxConstruction{
public String parseFromString(String str){ //impl };
}
If the user who add the class don't update the elementPrototypes list it may lead to hardly-catched bugs. I'd like to make them be awared of updating the list safely?
You could use an abstract implementation that "register" itself (in constructor) into Parser's elementPrototypes, something like:
public abstract class BaseSyntaxConstruction implements SyntaxConstruction {
protected BaseSyntaxConstruction() {
Parser.addElementPrototype(this);
}
}
public class Copy extends BaseSyntaxConstruction {
public String parseFromString(String str){
// impl
}
}
Note that you could also use reflection to "detect" SyntaxConstruction implementations
Following your comment, I think you might want to use an enum here to store implementations, no need to instantiate, no need to register (see values()):
enum SyntaxConstruction {
COPY {
#Override
public String parseFromString(String str){
// impl
}
},
// ...
;
public abstract String parseFromString(String str)
}

Categories

Resources