Question

I'm trying to realize an ADT for one of my programs, and I'm having difficulty implementing it correctly for use without error. Here is some sample code I'm working with:

//JavaApplication

package javaApplication;
import someADT.*;

public class JavaApplication {
    public JavaApplication () {
        abstractType a = new typeFor("Hello"); //Err1
    }

    public abstract class typeFor implements abstractType { //Err2
        public abstractType typeFor (String s) {
            //some code
        }
    }

    public static void main(String[] args) {
        JavaApplication j = new JavaApplication();
    }
}

Below is the list of accessor methods.

//abstractType implementation
package someADT;

public interface abstractType {
    public abstractType doSomethingA();
    public abstractType doSomethingB(abstractType a);
    public int doSomethingC(abstractType a);
}

I'm not entirely sure how to implement abstract types which should be obvious. I've commented some of the lines above with errors, which are:

Err1 = is abstract and cannot be instantiated
Err2 = attempting to assign weaker access privileges

I'm very new to this, but I can't find solid documentation on how to do it properly. I have lecture slides but I'll admit they're fairly barebones. I did use the example provided and just swapped my own stuff but kept the general syntax and I get these errors.

What is wrong with my implementation?

Was it helpful?

Solution

You are missing few things here:

  1. You can not instantiate an abstract class in Java
  2. A non-abstract class should implement all the abstract methods it inherits from a super class/interface
  3. Constructors can not have return type

OTHER TIPS

an abstract class canNOT extend an INTERFACE. It can only implement it. An interface cannot be instantiated. It can only be implemented by other classes or extended by other INTERFACES.

You could improve your code by doing the following:

public class JavaApplication {

    public JavaApplication () {
        abstractType a = (new typeFor()).typeFor("HELLO"); //Err1

    }

    public class typeFor implements abstractType { //Err2
        public abstractType typeFor (String s) {
            return null;
        }

    @Override
    public abstractType doSomethingA() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public abstractType doSomethingB(abstractType a) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int doSomethingC(abstractType a) {
        // TODO Auto-generated method stub
        return 0;
    }
    }

    public static void main(String[] args) {
        JavaApplication j = new JavaApplication();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top