Jump to content

Interface in the constructor parameters

I have an assignement for Data Structures and Algorithms and I am confused because I have the interface class in the class constructor and I do not understand how it works or how to use it. Here is my code,

// THIS IS THE CLASS
public class FindMin<E>  {

  public FindMin(Compare<E> comp) {
        if(smaller(min,(E)comp)){
            min = (E)comp;
            counter++;

        }
  }

// THIS IS THE INTERFACE
    public interface Compare<E> {
        public boolean equal(E e,E f);
        public boolean smaller (E e,E f);
    }

 

Link to comment
https://linustechtips.com/topic/1409309-interface-in-the-constructor-parameters/
Share on other sites

Link to post
Share on other sites

5 minutes ago, Ruben1 said:

I have an assignement for Data Structures and Algorithms and I am confused because I have the interface class in the class constructor and I do not understand how it works or how to use it.

To be clear, are you having issues with Java interfaces, Java classes, or the algorithm you're trying to implement using Java?

 

(I assume it's Java; walks like Java, talks like Java, must be Java)

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to post
Share on other sites

1 minute ago, AbydosOne said:

To be clear, are you having issues with Java interfaces, Java classes, or the algorithm you're trying to implement using Java?

 

(I assume it's Java; walks like Java, talks like Java, must be Java)

This is what they ask me to do the constructor takes as input an object implementing the Compare<E> interface. This object should be used to determine the smallest element insert. Hence, the ADT should work with all elements of a given class E for which we provide an object implementing the Compare<E> Interface. and I dont understand how the part of the object of the interface what does it mean and when I initialise the object what am I supposed to put in the constructor. Sorry if I wasnt clear in the first place.

Link to post
Share on other sites

1 minute ago, Ruben1 said:

This is what they ask me to do the constructor takes as input an object implementing the Compare<E> interface. This object should be used to determine the smallest element insert. Hence, the ADT should work with all elements of a given class E for which we provide an object implementing the Compare<E> Interface. and I dont understand how the part of the object of the interface what does it mean and when I initialise the object what am I supposed to put in the constructor. Sorry if I wasnt clear in the first place.

This example from W3 should help.

 

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

 

https://www.w3schools.com/java/java_interface.asp

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 9600X || GPU: RX 9070 XT|| Memory: 32GB || Cooler: Peerless Assassin || PSU: RM850e|| Case: Lian Li A3

Link to post
Share on other sites

1 minute ago, Slottr said:

This example from W3 should help.

 

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

 

https://www.w3schools.com/java/java_interface.asp

Thanks for the example but my confussion is in the parameters of the constructor I dont understand what has to go there because it seems as if it was an object from the interface but an interface doesnt have objects itself so I am really confused.

Link to post
Share on other sites

public class FindMin<E> {
    public FindMin(Compare<E> comp) {
    }
}

This constructor accepts any class that implements the "Compare<E>" interface. Your current implementation seem very weird though. Since you are constructing a new instance of FIndMin, where does "min" come from? You are also calling "smaller" as if it was a method in FindMin, but it is actually a method of the compare interface, so you need to call it on whatever object is passed into your constructor.

 

Casting the argument to E doesn't really make sense either. The interface guarantees that the object you have can be compared to E, but it isn't necessarily of type E itself. So this could actually result in a class cast exception. My example below shows a type-safe alternative to this.

 

The way to use your interface would be to implement it:

public class Number implements Compare<Number> {
    
}

You can now pass an instance of the Number class into your constructor. The constructor accepts any class that implements the Compare interface, which Number does, so it is acceptable.

Here's a concrete example that is usable:

public interface Compare<E> {
    // no need to use 'public' here, this is implicit for interface methods
	boolean smaller(E other);
	boolean equal(E other);
}

// Instead of using the interface as type argument, we use an object that implements the interface.
// This way we can return concrete objects rather than interfaces.
public class FindMin<E extends Compare<E>> {

    private final E min;

    public FindMin(final E e1, final E e2) {
        if (e1.smaller(e2)) {
            min = e1;
        } else {
            min = e2;
        }
    }

    public E getMin() {
        return min;
    }
}

// Here's an example class implementing the interface
public class Number implements Compare<Number> {

	private final int value;

	public Number(final int value) {
		this.value = value;
	}

	@Override
	public boolean smaller(final Number other) {
		return value < other.getValue();
	}

	@Override
	public boolean equal(final Number other) {
		return value == other.getValue();
	}

	public int getValue() {
		return value;
	}
}

// Some test code
final Number one = new Number(1);
final Number two = new Number(2);

final FindMin<Number> findMin = new FindMin<>(one, two);

final Number min = findMin.getMin();

assert min.equal(one) : "min and one should have the same value";
assert min == one : "min and one should actually be the same instance";

 

Remember to either quote or @mention others, so they are notified of your reply

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×