How To Enforce Any Class Which Implements Interface Should Also Implement Comparable Too

Dec 15, 2014

How do you enforce any class which implements an interface should also implement comparable too? Say for instance you may have an interface

public interface Task
{ ... }
public class DoThis implements Task { ... }
public class DoThis1 implements Task { ... }

I want all of the classes which implements the interface Task to implement comparable too. Of course I can just say implements Task, Comparable. But is there something which we could do from interface level, i mean interface Task level?

View Replies


ADVERTISEMENT

Widget Class That Implement Comparable Interface

Mar 15, 2014

Below is the requirements and code. I am getting the error CODELAB ANALYSIS: LOGICAL ERROR(S)We think you might want to consider using: >

Hints:

-Correct solutions that use equals almost certainly also uses high
-Correct solutions that use equals almost certainly also uses low

Assume the existence of a Widget class that implements the Comparable interface and thus has a compareTo method that accepts an Object parameter and returns an int . Write an efficient static method , getWidgetMatch, that has two parameters . The first parameter is a reference to a Widget object . The second parameter is a potentially very large array of Widget objects that has been sorted in ascending order based on the Widget compareTo method . The getWidgetMatch searches for an element in the array that matches the first parameter on the basis of the equals method and returns true if found and false otherwise.

public static boolean getWidgetMatch(Widget a, Widget[] b){
int bot=0;
int top=b.length-1;
int x = 0;
int y=0;
while (bot >= top)

[code]....

View Replies View Related

How To Implement Interface And Extend Class

Apr 12, 2014

how to 'implement' an interface and 'extend' a class. Now I want to try and recall the information by memory without using any reference material.
Implementing an interface...

Java Code: //This interface will hold information for cell phones//Like saying... you can't BE a cell phone unless you have this information, at the very least

public interface CellInfo {
public void model();
public void make();
public void androidVer();

}

//Now I implement the interface for a class called Galaxy, which is a class about a specific phone

public class Galaxy implements CellInfo
public void model() {
System.out.println("I'm a Galaxy S5.");
}

public void make() {
System.out.println("I'm made by Samsung.");

[code]....

View Replies View Related

Java Interface - Implement Method In Another Class

Sep 17, 2014

So I created an interface which has the method

int getCalls();

I am trying to implement this method in another class but I'm not sure how to do so. My attempt is:

public getCalls(){ return getCalls(); }

When I run the program it sends the following exception:

Exception in thread "main" java.lang.StackOverflowError
at FibonacciForget.getCalls(FibonacciForget.java:14)
and it highlights the [return getCalls();] part.

What is the correct way to implement the getCalls() method?

View Replies View Related

Servlets :: How To Know Which Class Will Implement Which Session Listener Interface

Jan 23, 2015

how it is decided which class will implement a session listener interface? Which class will implement HttpSessionListener? Which one will implement HttpSessionActivationListener, HttpSessionBindingListener or HttpSessionAttributeListener?

View Replies View Related

Method That Return Instance Of A Class That Implement Iterator Interface

Apr 14, 2015

I have been researching the Iterator and making a class implement iterable. I have seen this example shown below and was wondering how I could change this so that iterable() is not called upon in the main. I would like to be able to make a method that returns an instance of a class that implements the Iterator interface hopefully an inner class. This is because my program will not have a main and will be supplied with a main that includes a new Object with will use the iterator method.

import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");

[Code] ....

This is all I have been able to understand from what I want to do. This does not work and this is what I am trying to achieve

public class MyArrayList implements Iterable {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
 
[Code] ...

View Replies View Related

Using Comparable Interface Between Two Classes

Feb 13, 2014

I have the following code that will make linked list and order its elements using self referential objects. but i have the following error:
incompatible types

required: ListNode<T#2>
found: ListNode<T#1>
where T#1,T#2 are type-variables:
T#1 extends Comparable declared in method <T#1>insertInOrder(T#1)
T#2 extends Comparable declared in class OrderedList

import java.util.*;
public class ListNode<T> {
ListNode<T> nextNode;
T data;
public ListNode(T item)
{
this(item, null);

[code]...

View Replies View Related

Comparable And Iterable Interface

Jan 1, 2014

I have a task to create a Java OOP program, I have a class Team which requires a comparable and iterable interface, the only way I know how to do this is either:

public class Team implements Iterable <Mechanic>
or
public class Team implements Comparable <Mechanic>

How do I add both?

View Replies View Related

Overriding CompareTo From Comparable Interface

Oct 31, 2014

Here is my code:

/*
* Implement the Comparable interface on objects of type Order.
* Compare orderId, then productId. The lesser orderId should come first. If the orderIds match, then the lesser productId should come first.
*/

@Override
public int compareTo(Order ord) {
// TODO Auto-generated method stub
if(orderId > ord.orderId){
return 1;

[Code] ....

Here is the output:

Actual: 0
Expected: -1
Actual: -1
Expected: -1
Actual: 1
Expected: 1
Actual: 1
Expected: 1
Actual: 0
Expected: 0
Actual: 0
Expected: 0

In short, the "Actual" is what my code produces and the "Expected" is what it is supposed to produce. As you can see, only the first one is mismatching... I'll admit, the comment section above the method is confusing and I wasn't exactly sure what it wants me to do, but I thought I figured it out. I just don't see how 5/6 of these tests can work and the 6th one not.

View Replies View Related

Comparable Interface For Primitive Types

Apr 16, 2014

Why is it necessary to implement the comparable interface for primitive types and not for classes such as Integer, String etc . . . ?

View Replies View Related

Ball Object Which Implements Runnable Interface And Traces Various Positions Of A Ball

Feb 11, 2014

a) I have a Ball Object which implements the Runnable interface and traces the various positions of a ball.

b) I then have a Ball_Bounce JPanel inside a JFrame which creates two instances of the Ball object and then paints them to the JPanel.

As per my understanding, when the main() program in Ball_Bounce.java is started, there a total of three threads running in this program, one for each ball and one for the main(). What I cannot understand is whenever the balls collide, I end up getting the "Collision" message twice even though the collision is checked only in the main() thread.

[#]public class Ball implements Runnable
{
private boolean xUp, yUp, xUp1, yUp1;
private int x, y, xDx, yDy;
private final int MAX_X = 500, MAX_Y = 500;
private boolean flag = true;
private static Thread ball;
 
[code]...

View Replies View Related

Create SmartString Class That Implements SmartStringInterface Class

Jun 3, 2014

The assignment is to create a SmartString class that implements a SmartStringInterface class (created by professor) and implements a few methods. We are basically taking a string and then taking various substrings and inserting, deleting them and undoing changes as well. Here are the methods in the interface to use along with the parameters.

public interface SmartStringInterface {
public void insert(int pos, String sstring);
public void delete(int pos, int count);
public void undo();
public String toString();

The Undo is supposed to be able to be called multiple times (to be tested using a driver program that we must create) but the part that's got me is that the changes are only supposed to be stored. Currently, I am storing the "new" string after each change onto a stack, so that undo can just pop off the stack and it will revert to the previous string. Professor said that was wrong, so I don't know how to do it. Here is what I have so far (some of the code we have is using default StackADT stuff from our book, so if you need that I can post as well. You can see in the undo method where I currently save the string. We can use multiple stacks if needed, but the less the better. Must use at least 1. The exception code is already coded for us in another file also. I am only having to code these methods and the driver to test.

import java.util.Arrays;
public class ArrayStack<T> implements StackADT<T>
private final static int DEFAULT_CAPACITY = 100
private int top;
private T[] stack;

[code]...

View Replies View Related

Creating Instance Of A Class That Implements Runnable

Jul 31, 2014

I'm reading about threads In Head First Java and the way an Instance of a class that Implements Runnable Is created confuses me a little.

public class MyRunnable implements Runnable ......
Runnable ThreadJob = new MyRunnable();

I thought I had to use this syntax :

MyRunnable ThreadJob =new MyRunnable();

View Replies View Related

Implement Attached Interface

Nov 16, 2014

I need to implement the attached interface ("Locality"). In the attached UML diagram it has a 1 on 1 relationship with the class "Team". I don't know if this can be somehow implemented in Java. Can I create the attribute "team" in the Locality interface and let it be used by the "Town" and "City" classes? Could it be better to implement it as an abstract class instead?

View Replies View Related

Implement Method Inside Interface

Sep 3, 2014

if i call a class that implements an interface the method inside the interface will be triggered automatically by the compiler or happens only in the observer pattern? i keep simple to be surr the message came across, a typical example would be a listener on a button, or a collection that calls comparator)

View Replies View Related

Call Method In All Objects Which Implement Certain Interface

Apr 15, 2015

if some of you worked with Unity Game engine (C#) the idea is that game has main loop and once per cycle it call for example Update() method in all objects which implement certain interface.

I would like to repeat such pattern in Java for another another program, not even game related, but I would still need a main loop and event driven behaviour with async call backsSo question is how to implement the fallowing scenario:

Imagine i have interface which implement some methods and one of them is Execute()

I have the main controller class which implement main loop, also multiple other classes which implement the same interface with method Execute(). How can i call this Execute() method on all objects which implement that interface each loop cycle?

Should i keep and track reference of each object which was implemented with this interface and go through inner "for" loop trough each reference and call manually Execute() method in each of them?what if each object implementing interface have to run Execute() method simultaneously? in parallel independent from each other?

Referring back to Unity engine and their Update() method - there is exactly the same situation:you can have multiple objects with script attached, thats script implement interface which has multiple methods and one of them is Update() and once per cycle all objects with that Update() method will be executed in parallel independently

View Replies View Related

Additional Methods From Specific Classes That Implement Interface

Jan 8, 2014

I am writing a game in Java for Android (although my question isn't Android or Game Dev specific).

I have a SceneManager class and a Scene interface and then various other classes that implement the Scene interface (Code at the end of this post).

Basically, in my MainGame class (which also implements the Scene Interface for Touch Event capturing purposes) I hold the bulk of my game code. Methods in this class are then called from my Level classes. (most of these are needed in all levels so it makes sense to hold them here and call them from the levels to eliminate unnecessary code duplication)

So, I have Level1, Level2......... Level20 classes which all implement Scene.

Now, the problem comes because in only 2 of my Levels something can happen (that can't in the other 18) and I need to run a response method in these 2 levels (the method isn't exactly the same, the response to this event happening is different for both levels).

To run common methods from my classes, I use my Scene Manager like this:

SceneManager.getInstance().getCurrentScene().updateLogic();
SceneManager.getInstance().getCurrentScene().render();

(The above is from my gameloop) - So it will run the updateLogic(); and render(); methods from whichever is the current scene (Level).

Scene is changed like so:

SceneManager.getInstance().setCurrentScene(LevelX);

This works great as all Level's have an updateLogic(); and render(); method.

So from my mainGame class, I am doing something like : (pseudo code)

public void checkIfSomethingHappened(){
if (something happens){
if (currentLevel==5){
Level5.response();}

[Code]....

The above would be called from my 2 level classes. So something like:

MainGame.checkIfSomethingHappened(); //Called in addition to the normal methods that make up that level

I don't really want to have this (second) 'if' statement here in the middle of my performance critical game loop.

What I'm after is something like this:

if (something happens){
SceneManager.getInstance().getCurrentScene().response();
}

However, this would require me to put stubs in the other 18 classes.

I'm thinking there must be a way to do this as the SceneManager already knows the current scene so it seems a waste checking it again via an if (or switch) statement. What is the best way to do this without having to put stubs into classes that don't require this method?

View Replies View Related

Trying To Implement Interface - The Method DoSomething Is Undefined For The Type B

Dec 2, 2014

Let's say we have situation like this:

abstract class A
class B extends A
class C extends B
class D extends C implements SomeInterface

I'm trying to implement a method "doSomething" declared in SomeInterface in class D. While trying to call doSomething in main I get the error message ”The method doSomething is undefined for the type B”

This is my code i main:

B container = new D("1,2,3,4,5,6,7,8");
System.out.println(container.doSomething());

I need container to be an object of type B, because it goes later into a list of type B. According to what I've been told, the only file I need to edit to make this work is class D.

View Replies View Related

Comparable Class - Create Priority Queue For Airline Passengers

Oct 9, 2014

My assignment was to create a priority queue for Airline Passengers. Here is what I have done so far:

//Driver

package priorityqueuestandby; 
import java.util.NoSuchElementException;
import javax.swing.JOptionPane;
public class PriorityQueueStandBy {
public static void main(String[] args) {

[Code] .....

So the part that I cant figure out is:

When a standby passenger is to be enqueued into the priority queue, it must be done so that at the moment of each dequeue operation, the item at the head of the queue is the standby passenger with the longest longevity, and also so that passengers with the same longevity are dequeued in a first-come-first-served fashion.

he says that we need to "Make your program so that it extends Comparable and implements the compareTo() method properly..."

So I was looking at the Comparable class and I could't find a compareTo() method... I am not confident I know how extends works either. I am assuming I need a new class if I am going to be extending another class. Right now I am taking in longevity as a String and converting it to an int because my last ditch effort is going to be to set up a loop that will organize longevity into a/an circular array based on the size of the incoming integer.

View Replies View Related

Interface Class And Object Class Is Compiling Symbol Errors

Nov 16, 2014

I am a beginner here at JAVA and I am trying to program a Gratuity Calculator using both interface class and object class but it keeps on compiling with errors saying "cannot find symbol".I tried everything to fix it but it just keeps on stating symbol.

[CODE]
public class GratuityCalculator extends JFrame
{
/* declarations */
 
// color objects
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
Color light_gray = new Color(192, 192, 192);
 
[code]....

View Replies View Related

How To Implement A Variable Into Another Class

Apr 13, 2015

I would like to implement a variable in a class that is used in another class, how can I do that?

I have a Mall class and a Customer class I would like to associate the position of the customer that is in the Mall class and also implement the same in the Customer class.

Here is a small part of the code without all the methods.

//the two objects
Mall m = new Mall("RandomMall",50,30);
Customer c1= new Customer("Jack",1240);
//the first part of the mall class without the methods
class Mall{
private String name;
private int width,length;
String[][]grid = new String[width][length];

[code]...

View Replies View Related

ERROR When Try To Implement A Class

Dec 6, 2014

I'm writing a simple queue program using a netbeans as a GUI program I've used netbeans GUI editor to create the GUI my main problem was I've written the queuing code to a button function it works but it runs only once and the queue becomes empty on the second run. So I implemented a class which will create the queue outside the button click event but when I do that I get a Symbol not found: method error . The place where I get the error:

addStd1.setText("Add Student");
addStd1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStd1ActionPerformed(evt);
}

My button function with the class:

class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {

[code]....

View Replies View Related

Class Can't Implement Chart

Mar 10, 2014

i'm getting cryptic error messages for the following code:

class MyChar implements CharSequence{
private String s;

public MyChar(String input)
{
StringBuilder b = new StringBuilder(input);
b.reverse();
this.s = b.toString();

[code]....

it's telling me something's wrong with the class modifier and that my class can't implement chart

View Replies View Related

How To Implement Own String Class

Feb 12, 2015

I am a beginner at Java programming. how to implement my own String class, but I have to provide my own implementation for the following methods:

public MyString1(char[ ] chars)
public char charAt(int index)
public int length( )
ublic MyString1 substring(int begin, int end)
public MyString1 toLowerCase( )

[code]....

I have looked through the API, but I don't really understand where to start.

View Replies View Related

How To Implement Class DynamicArrayStack

Feb 9, 2015

While learning how to implement the class DynamicArrayStack, I've run into some operators and syntax I'm unfamiliar with!

public class DynamicArrayStack{
protected int capacity
public static int MINCAPACITY=1<<15;
protected int[] stackRep;
protected int top = -1;
//initializes stack to use an array of default length
public DynamicArrayStack()
this(CAPACITY)

[code]....

View Replies View Related

When To Use Interface And Abstract Class

Apr 17, 2014

I know whats the interfaces and abstract class and also know that difference between interface and abstract class,but here my doubt is eventhough abstract class more advantage than the interface,then why should we use interfaces and when?

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved