Abstract class cannot be instantiated - java

I had to create this point program a year ago, a year ago it worked fine. Now I have to revisit it and upon compiling and trying to run it I ran into the error of the fact that an abstract class cannot be instantiated. I have done some looking around online and figured out that some update or sort with Java has made it where the method of using PointClass point1 = new PointClass(); is no longer valid and will through an error.
I have yet to find an answer for fixing the error when trying to instantiate the class using a driver program. I also saw that in order to use an abstract class now, a subclass must be present. The thing is is that due to the instructions of the program I cannot use a subclass. Only the driver and the point class.
The program is very simple, just declare some points and call them from the abstract class in order to print to the screen. I need some help on figuring out the updated method to make this work again without the instantiated error.
The PointClass
public abstract class PointClass {
private int pointX;
private int pointY;
//set instance variables
public PointClass() { this.pointX = 10; this.pointY = 10; }
public PointClass(int x, int y){ this.pointX = x; this.pointY = y; }
//make getters and setters
public void setPointX(int x) { this.pointX = x; }
public void setPointY(int y) { this.pointY = y; }
public int getPointX() { return this.pointX; }
public int getPointY() { return this.pointY; }
//make string for format with driver
public String toString() { return "x = " + this.pointX + " y = " + this.pointY; }
}
The Driver
public class PointTest {
public static void main(String[] args){
System.out.println();
PointClass point1 = new PointClass(); //set point1 as no argument
PointClass point2 = new PointClass(11, 24); // set point2 as argument with x and y
System.out.println("Point1: " + point1); //display point1 from toString method
System.out.println();
System.out.println("Point2: " + point2); //display point2 from toString method
System.out.println("---------------------");
}
}

The best thing to do would be to remove the abstract keyword. There's no need for it. Point has no abstract methods.
If you can't do that for whatever reason, you can create inline anonymous classes by adding curly braces after each instantiation:
PointClass point1 = new PointClass() { };
PointClass point2 = new PointClass(11, 24) { };
By the way, your claim that this used to work is incorrect. It has never been possible to directly instantiate an abstract class. That is in fact the entire point of the keyword, to prevent a class from being instantiated.

Related

Calling an instance method from a different class

The purpose of this program is to test another program I created.
It's called ComplexNumber. This class has everything from add, multiply, dividing complex numbers numbers and stuff and they are all in methods. The teacher wants us to create a testing class, here is what I have so far.
The problem I am having is calling the methods from the ComplexNumber class. For example: I tried calling the plus method, this method takes in two ComplexNumbers and adds them up. So far I've been testing these methods using the interaction panel and it has worked great. The way I called them in the interaction panel was by doing first.plus(Second) and this would give the final values.
On the testing class, I am having difficulty calling the methods.
I know that I need the class name.
I tried:
ComplexNumber.first.plus(second)
But it didn't work.
How can I do it?
Here is my code:
class TestComplexNumber
{
double real;
double imag;
public TestComplexNumber(double a, double b)
{
this.real=a;
if ((b<1000)&&(b>-1000))
this.imag=b;
else
{
this.imag=0;
System.out.println("The value you typed in for imag is <1000 or >-1000, value of imag is assigned the value of 0.");
}
}
public String toString()
{
double real,imag;
real=this.real;
imag=this.imag;
if (((real<0)||(real>0))&&(imag%1!=0))
{
if (roundThreeDecimals(imag)>0)
return ""+roundThreeDecimals(real)+"+"+roundThreeDecimals(imag)+"i";
else
return ""+roundThreeDecimals(real)+""+roundThreeDecimals(imag)+"i";
}
else if ((real%1!=0)&&(imag!=0))
return ""+roundThreeDecimals(real)+"+"+(int)imag+"i";
else if((real==0)&&(imag%1!=0))
return ""+imag+"i";
else if ((real==0)&&(imag !=0))
return ""+(int)imag+"i";
else if ((imag==0)&&(real!=0))
return ""+(int)real+"";
else if (((real<0)||(real>0))&&(imag<0))
return ""+(int)real+"-"+(int)Math.abs(imag)+"i";
else if((real!=0)&&(imag!=0))
return ""+(int)real+"+"+(int)imag+"i";
else
return "";
}
public static double roundThreeDecimals(double c)
{
double temp = c*1000;
temp = Math.round(temp);
temp = temp /1000;
return temp;
}
public static void main(String args[])
{
for(int i=0;i<1;i++)
{
//Testing decimal values
TestComplexNumber first=new TestComplexNumber((int)(Math.random()*100)-(int)(Math.random()*100),(Math.random()*100));
TestComplexNumber second=new TestComplexNumber((Math.random()*100),(Math.random()*100)-(int)(Math.random()*100));
//Testing whole values
TestComplexNumber third=new TestComplexNumber((int)(Math.random()*100)-(int)(Math.random()*100),(int)(Math.random()*100));
TestComplexNumber fourth=new TestComplexNumber((Math.random()*100)-(int)(Math.random()*100),(int)(Math.random()*100));
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
System.out.println("Test value for plus:"+first+second+" which added="+plus(second));
}
}
}
Example of a method on the ComplexNumber class:
public ComplexNumber plus(ComplexNumber other) {
ComplexNumber sum= new ComplexNumber(this.real,this.getImag());
sum.real=(this.real)+(other.real);
sum.setImag((this.getImag())+(other.getImag()));
return sum;
}
public class Tester {
public static void main(String [] args) {
// create two objects of ComplexNumbers with whatever values you like
ComplexNumber numA = new ComplexNumber(....);
ComplexNumber numB = new ComplexNumber(....);
// then add them and store the returned reference into a new variable
ComplexNumber result = numA.plus(numB);
// print the number however you like
System.out.println(result.real + " + i" + result.getImag());
}
}
I don't know what this "interaction panel" is, but first.plus(second) from there should work no different than in the actual code.
plus is the method called in the first instance.
The method should not be static, as in static ComplexNumber plus(ComplexNumber other), so you do not need the class name to use it.
In conclusion, to call an instance method from another class, you need an instance, which you have should have four calls to new ComplexNumber(), and not new TestComplexNumber()
My teacher said i have to create the testing program in a new class and not on the ComplexNumber class
I think your real issue is that you have this class TestComplexNumber, which is only intended to be a "test class" (only need a main method), not a re-creation of the ComplexNumber class, which seems to be what you've done (since I see no plus, mutiply, divide, etc).
And if you are supposed to actually create a "test suite", not a main method, then you should use JUnit, or other testing framework

Java - Inheritance regarding constructors

So, I'm trying to practice my java skills by applying it to some math homework and making a frequency distribution chart using inheritance. In my head, I envision it as a frequency distribution (parent class = FreqDist) that can have multiple "MyStatClasses" (in the form of the MyStatClass array). Each FreqDist has variables that span across all MyStatClasses which is why I put them in the parent class. However, when I call the MyStatClass constructor, my program gets a StackOverflowError. I think this is because the super(s, i) line calls back to the FreqDist constructor and starts over, causing an infinite loop. Assuming this is the case, how would I fix this?
Ideally, I'd like to access my MyStatClass array and grab values that only apply to that MyStatClass, but I cannot get it to work.
public class FreqDist {
private MyStatClass[] freqClasses;
private double[] dblValuesArray;
private int intNumberOfClasses;
private double dblMax;
private double dblMin;
private int intClassWidth;
public FreqDist(String strValues, int intNumOfClasses) {
System.out.println("This is the beginning of the FreqDist constructor...");
dblValuesArray = getDoubleValues(strValues);
intNumberOfClasses = intNumOfClasses;
dblMin = dblValuesArray[0];
dblMax = dblValuesArray[dblValuesArray.length - 1];
intClassWidth = (int)Math.ceil((dblMax - dblMin) / intNumberOfClasses);
freqClasses = new MyStatClass[intNumberOfClasses];
for (int x = 0; x < freqClasses.length; x++) {
freqClasses[x] = new MyStatClass(strValues, intNumOfClasses);
}
}
public double[] getDoubleValues(String strValues) {
String[] strValuesArray = strValues.trim().split(" ");
dblValuesArray = new double[strValuesArray.length];
for (int x = 0; x < strValuesArray.length; x++) {
dblValuesArray[x] = Double.parseDouble(strValuesArray[x]);
}
Arrays.sort(dblValuesArray);
return dblValuesArray;
}
public int getNumberOfClasses() {
return intNumberOfClasses;
}
public double getMin() {
return dblMin;
}
public double getMax() {
return dblMax;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What are the values? ");
String values = scan.nextLine();
System.out.print("How many classes? ");
int classes = scan.nextInt();
FreqDist fd = new FreqDist(values, classes);
}
}
public class MyStatClass extends FreqDist {
public MyStatClass(String s, int i) {
super(s, i);
}
}
Ok so this is mostly an issue with a flaw in your design.
From what I understand FreqDist is a class that should contain an array of MyStatClass. You want them to have the same properties so you make MyStatClass extend FreqDist. However when you call FreqDist it MyStatClass which Calls a new MyStatClass over and over and over.
One way to solve this is to create a new class that has the shared properties you want FreqDist and MyStatClass to have, and have those two classes inherit from said class. Then create separate constructors for FreqDist and MyStatClass.
A parent type should never refer to its own subtypes, as yours does. Her the parent initializes subtype instances, which require that each initialize the parent type, which initializes subtype instances, which initialize their parent type, which initializes... KABLOOEY!

Why my program no work ? keep getting cannot find symbol error?

I keep getting cannot find symbol error when trying to create the subclass h object in my main code. Would someone please be able to help ? Thanks.
It seems like the main program is accepting the inhtt object but when I try to call h object it says that it cannot find symbol and asks me to create the h object.
public class inhtt {
//class methods
public int thing;
public int stuff ;
public int otherstuff;
// constructor based on parameters
public inhtt( int x, int y, int z){
thing = x;
stuff = y;
otherstuff = z;
}
void showmain (){
System.out.println("thing is " + thing);
System.out.println("stuff is " + stuff);
System.out.println("otherstuff is " + otherstuff);
}
public class h extends inhtt {
int beard;
h( int x, int y, int z, int a){
super(x,y,z);
beard = a;
}
void shownewa(){
System.out.println("beard is" +beard);
}
}
}
* #author New User
*/
public class runraffharsh {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
inhtt base = new inhtt(1,1,1);
base.showmain();
h = new h(1,1,1,1);
h.shownew();
// raff beard = new raff(1,1,1,1);
// beard.showbeard();
//
}
}
There are multiple problems with this code:
h is a inner class to inhtt. Since it is not static, you'll need to use something like base.new h(1,1,1,1); to instantiate it.
You need to declare a variable to assign your new h instance to. Try something like inhtt.h h = base.new h(1,1,1,1); for the whole line.
h (the class) has no method named shownew. It has a method named shownewa.
runraffharsh and inhtt are both public classes. They need to be in separate files.
The comment block at the top of runraffharsh is not opened properly.
You have problem with inherited class h's reference. And you defined showewa() but tried to access shownew()

Syntax error on "x", VariableDeclaratorld expected after this

class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
ranx1.x = 100;
You need to declare your variables as "public" if you are trying to access from a class that is not in the same package.
I guess your problem is you are trying to access to that attribute from a class that is in another package, you should declare the atrributes as public to gain access to them. But this solution wouldn't be totally correct, a better approach is declaring them as private and creating public getters and setters to access/modify them.
Said that, you should post a working example, that piece code does not compile because you are trying to execute code that is out of any class... and I'm not sure what you are trying to do with the curly braces before the if clause.
when you careate a class, every member has a control access.
when you don't state the control access like:
public x;
protected fc;
private Tcol;
they all get default private.
you can't access private members from outside the class.
do:
class anyName
{
public int Tcol = 0;
public int fc = 0;
public int x = 0;
public float randx = (random(1, 1000));
public float randy = (random (0, 600));
public int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
whoever, i must point out that most times it's not recommended to set members access as public and you should learn about getter and setters.
now i hope the rest of your code is in a main function and in a main class, but if not it should be like so:
public class Main
{
public static void main(String[]args){
anyName ranx1 = new anyName();
ranx1.x = 100;
}
}
First of all you cannot access sub class veriables like that. If you want to access you should make this
public class ExampleApp {
class anyName
{
int x = 0;
}
public static void main(String[]args){
ExampleApp ea = new ExampleApp();
ExampleApp.anyName ranx1= ea.new anyName();
ranx1.x =100;
}
}
Or you can use them inside of the class with method
public void method() {
anyName ea = new anyName();
ea.x=100;
}
you cannot use your veriables private if you want to access them.Secondly if you want to use this libraries you cant use innerclass. Inside of innerclass you cannot access libraries because java sees it in diffrent package. If you make it public class and import Math you can use it otherwise you should make method for your ellipse, random .

Java, Array of Objects

This is a trivial question, but my Java is rusty and it's got me stumped; I am getting a null-pointer exception. It may be obvious what I am trying to do based on the code below - but I will explain...
I need an array of objects and I don't want to create another file. For this trivial project, I do not want getters and setters. I have seen an example similar to below that uses a linked list based on a class that is located inside of another class. But, I am more proficient with arrays than linked lists, so I want to use arrays.
public class Ztest {
Stuff[] st = new Stuff[2];
public Ztest(){
}
class Stuff{
public String x;
public boolean y;
public Stuff(){}
}
public static void main(String args[]){
Ztest test = new Ztest();
test.st[0].x = "hello";
test.st[0].y = true;
test.st[1].x = "world";
test.st[1].y = false;
System.out.println(test.st[0].x);
System.out.println(test.st[0].y);
System.out.println(test.st[1].x);
System.out.println(test.st[1].y);
}
}
You need to assign a value to st[0] and st[1] first:
test.st[0] = new Stuff();
test.st[1] = new Stuff();
Java allocates null for object values in new arrays. You'll need something like test.st[0] = new Stuff() before using it.
You need test.st[0]=new Stuff(); etc. since Stuff[] st = new Stuff[2]; creates an array but the elements (references) are still null.
In terms of C/C++ this would be Stuff** st = new Stuff*[2];, i.e. the st is an array of pointers to Stuff instances, whereas the pointers still point to nothing yet.
You need to put an instance of Stuff into test.st[0] and test.st[1].
You can try this if you want to use a list.
static class Stuff {
public String x;
public boolean y;
// generated by my IDE.
Stuff(String x, boolean y) {
this.x = x;
this.y = y;
}
// generated by my IDE.
public String toString() {
return "Stuff{" + "x='" + x + '\'' + ", y=" + y + '}';
}
}
public static void main(String args[]) {
List<Stuff> list = new ArrayList<Stuff>();
list.add(new Stuff("hello", true));
list.add(new Stuff("world", false));
System.out.println(list);
}
prints
[Stuff{x='hello', y=true}, Stuff{x='world', y=false}]

Categories