I have to write a program that has a constructor without parameters. I created another short program as an example to show what I do not understand.
So I have a class with the main-method:
public class Dog {
public static void main(String[] args) {
CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40);
System.out.println(Dog1.toString());
}
}
Now implemented another class:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog(/*int size, int kilogram*/) {
// this.size = size;
// this.kilogram = kilogram;
}
public double getSize() {
return size;
}
public double getKilogram() {
return kilogram;
}
public String toString() {
return "The Dog is " + getSize() + " cm and " + getKilogram() + " kg";
}
}
In the class "CharacteristicsOfTheDog" in "public CharacteristicsOfTheDog()" I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?
Keep your no-arg constructor and then add setters for your properties:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog() {
}
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
In your other class, call:
CharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();
dog.setSize(20);
dog.setKilogram(40);
As a suggestion, the naming of your class as CharacteristicsOfTheDog is rather literal and stating the obvious. Properties and methods of a class are what describes the characteristics of a class in terms of it's properties and behavior. If you just name your class Dog, that would be perfect. No need to state the obvious.
Unless CharacteristicsOfTheDog is a subclass or you have a constructor with parameters, you don't need an empty constructor. Just omit it. The following works just fine.
If the parent class has a constructor with arguments, then the parent class will need an explicit empty constructor, but the following should still work.
CharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();
cotd.setKilogram(100);
}
class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
Depending on your use case, you might want to make the Characteristics class an interface and implement it.
Related
Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
first off I tried researching my problem but I have no idea how to word my question ... so I am not sure if there is a question out there that solves my problem and also not sure if this is the best wording for my question either.
So, I have a Superclass Shape
public abstract class Shape {
protected String name;
protected String type;
public Shape(){
name = "";
type = "";
}
public void print (){
System.out.printf("Name = %s, Type = %s", name, type);
}
}
and a Subclass 2D
public abstract class TwoDimensionalShape extends Shape{
protected double length;
protected double area;
public TwoDimensionalShape(double length){
if (length<0.0)
throw new IllegalArgumentException("ERROR: POSITIVE NUMBER REQUIRED");
this.length = length;
type = "Two Dimensional Shape";
}
public abstract void getArea();
#Override
public void print(){
System.out.printf("Name = %s, Type = %s, Length of side = %d, Area = %d",
name, type, length, area);
}
}
along with several smaller subclasses that extend off 2D (and another almost identical class 3D). My problem is with the test code, it doesn't calculate area. Class Test code
Circle S1 = new Circle(2.5);
etc.
shapesArray[0] = S1;
etc.
for(Shape CS : shapesArray){
CS.getArea();
if(CS.Type == "Three Dimensional Shape"){
CS.getVolume();
}
CS.print();
System.out.println(" ");
}
}
I removed the getArea and getVolume methods and the print statement worked fine. Which lead me to think there is a problem with the way each subclass interacts with the superclass, however, the subclass print methods override and return the correct values (except for area :( )
With the area and volume commands, the code doesn't compile and I get this error
ShapeTest.java:25: error: cannot find symbol
CS.getArea();
three times.
Here is one of the subclasses, in case it holds important info needed for a solution.
public class Circle extends TwoDimensionalShape {
public Circle(double length){
super(length);
name = "Circle";
}
#Override
public void getArea(){
area = Math.PI * length * length;
}
#Override
public void print(){
System.out.printf("Name = %s, Type = %s, Radius = %f, Area = %f",
name, type, length, area);
}
}
I am not experienced enough to understand the problem entirely and I have been changing loops, location of variables and methods in the classes but I have not made progress. I thank you for reading this long question and id appreciate any help you can offer.
Your type Shape doesn't declare that method.
The compiler doesn't know that you intend to put TwoDimensionalShape objects into that array. It only see that you said: this array contains Shapes; and shapes do no have those other two methods!
So you could do:
declare that array to contain only TwoDimensionalShape objects. Of course, then you can't add 3D
use if (thing is instanceof TwoDimensionalShape) { and then cast to that type
And then: you dont need a string type. All objects have a class; and that class already defines its exact type. That is why you use instanceof to determine types; not by adding a string field and comparing that string (the wrong way with ==) to other strings!
Your super most class Shape should have all the methods you want to access through polymorphic feature of java.
One would assign a sub-type instance of to a supertype variable to handle all possible subtype classes in a uniform fashion, e.g. using methods declared (but possibly overriden) by the supertype class.
I have made minor changes to your classes.
abstract class Shape {
protected String name;
protected String type;
public Shape() {
name = "";
type = "";
}
public void print() {
System.out.printf("Name = %s, Type = %s", name, type);
}
public abstract void getArea();
public abstract void getVolume();
}
// ----------------
abstract class TwoDimensionalShape extends Shape {
protected double length;
protected double area;
public TwoDimensionalShape(double length) {
if (length < 0.0)
throw new IllegalArgumentException(
"ERROR: POSITIVE NUMBER REQUIRED");
this.length = length;
type = "Two Dimensional Shape";
}
#Override
public void print() {
System.out.printf(
"Name = %s, Type = %s, Length of side = %d, Area = %d", name,
type, length, area);
}
}
//------------------
class Circle extends TwoDimensionalShape {
public Circle(double length) {
super(length);
name = "Circle";
}
#Override
public void getArea() {
area = Math.PI * length * length;
}
#Override
public void print() {
System.out.printf("Name = %s, Type = %s, Radius = %f, Area = %f", name,
type, length, area);
}
#Override
public void getVolume() {
System.out.println("Vaolume method invoked");
}
}
//------------------
public class Dim {
public static void main(String[] args) {
Shape[] shapesArray = new Shape[10];
Circle S1 = new Circle(2.5);
shapesArray[0] = S1;
for (Shape CS : shapesArray) {
if (CS != null) {
CS.getArea();
if (CS.type.equals("Three Dimensional Shape")) {
CS.getVolume();
}
CS.print();
System.out.println(" ");
}
}
}
}
I am trying to instantiate an object (created in a "EmptySea" subclass of "Ship" class) into another "Ocean" class to fill an array with "EmptySea" objects.
Error is "EmptySea cannot be resolved to a type."
Here is my Ocean class code:
public class Ocean {
// Instance variables.
public Ship[][] ships = new Ship[10][10];
public int shotsFired;
public int hitCount;
// Constructor.
public Ocean() {
shotsFired = 0;
hitCount = 0;
for (int row = 0; row < ships.length; row++) {
for (int column = 0; column < ships[row].length; column++) {
ships[row][column] = new EmptySea();
public abstract class Ship {
// Instance variables.
private int bowRow;
private int bowColumn;
private int length;
private boolean horizontal;
private boolean[] hit = new boolean[4];
// No constructor needed for Ship class.
// Methods (too many to show).
public class EmptySea extends Ship {
// Constructor.
EmptySea() {
length = 1;
}
// Inherited methods to define.
int getLength() {
return length = 1;
}
String getShipType() {
return "Empty";
}
#Override
boolean shootAt(int row, int column) {
return false;
}
#Override
boolean isSunk() {
return false;
}
#Override
public String toString() {
return "-";
}
}
The ships array has been properly declared as an instance variable in Ocean class. Basically, it is not letting me put the EmptySea() object (the code for the "Ship" class and its "EmptySea" subclass runs correctly).
Do I need to somehow reference the superclass in this case?
If there's an easier way to do it, I can't do it that way (this way is specified in assignment).
Learn about the difference between a static nested class and an instance nested class.
Some other SO question on the same.
Short term: declare your inner EmptySea class with static, then read/understand why - in brief, without static an EmptySea instance cannot be created outside the context of a Ship instance.
I want each element of an enum to have different variables but I can't reach them.
public class Employee {
public GENERAL[] general = GENERAL.values();
public static void main(String[] args) {
Employee e = new Employee();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
}
enum GENERAL{
INCOME{
public int salary;
public int tips;
},SATIFACTION{
//some variables
},EFFICIENCY{
//some variables
};
}
}
I've tried casting to (GENERAL.INCOME) but it didn't work. Is there a way to do it? If this is not possible, what is the best work around? Thanks in advance.
Try defining variables at enum level rather than individual elements:
public static void main(String[] args) {
MainClass e = new MainClass();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
System.out.println(e.general[GENERAL.INCOME.ordinal()].salary);
}
enum GENERAL{
INCOME(0,0), SATIFACTION(0, 0), EFFICIENCY(0,0);
int salary;
int tips;
GENERAL(int salary, int tips){
this.salary = salary;
this.tips = tips;
}
}
This is because INCOME is an anonymous subclass of GENERAL, it is something like this
static class GENERAL {
public static GENERAL INCOME = new GENERAL() {
public int salary;
public int tips;
};
}
there is no way to access fields of an anonymous class in Java (except reflection)
This is the cleanest way I can do it. I still have an array that I can use to iterate. Each element of the General holds its own variables. Each element has an ordinal to use as the index number.
The problem with this approach is this cannot make use of GENERAL.values(). If a new element is added later, It must be added to the getList() method manually and in the correct order. It is easy to make mistakes when adding new elements to the code.
public class Employee {
public Object general[] = General.getList();
public static void main(String[] args) {
Employee e = new Employee();
General.Income i = (General.Income) e.general[General.Income.ordinal];
i.salary = 10; //eclipse doesn't let me to combine these 2 lines into 1 expressions.
System.out.println(i.salary);
// following lines demonstrates that the salary of the e.general[General.Income.ordinal] is changed. Not just the i.
General.Income t = (General.Income) e.general[General.Income.ordinal];
System.out.println(t.salary);
}
public static class General {
public static Object[] getList() {
Object general[] = { new Income(), new Satisfaction(), new Efficiency() };
return general;
}
public static class Income {
public static final int ordinal = 0;
public int salary;
public int tips;
}
public static class Satisfaction {
public static final int ordinal() {return 1;}//using method instead of int saves memory. (8 bytes I think. Neglettable).
// some variables
}
public static class Efficiency {
public static final int ordinal = 2;
// some variables
}
}
}
If each enumeration would contain a single value, why not use that?
You can even add a method to retrieve some descriptive name:
enum General {
INCOME, SATIFACTION, EFFICIENCY;
int value = 0;
String getName() {
switch(this) {
case INCOME:
return "salary";
case SATIFACTION:
return "etc";
}
}
}
These can be set/get by General.values()[i].value and General.INCOME.value or add setValue(int value) and getValue() methods and make value private.
I am trying to understand extending inner classes in Java. I have read around but nothing I found quite answers my question. So here goes...
I have...
public class Pie{
protected Slice[] slices;
// Pie constructor
public Pie(int n){
sliceGenerator(n)
}
private void sliceGenerator(int n){
slices = new Slice[n];
final float sweepAngle = 360.0f/(float)n;
float startAngle = 0;
for (int i=0;i<n;i++){
slices[i] = new Slice(startAngle);
startAngle += sweepAngle;
}
}
#Override
public String toString(){
for (Slice s:slices){
s.toString();
}
}
// Inner class...
public class Slice{
public Slice(float startAngle){
//set some private fields based on startAngle and generic pie
}
#Override
public String toString(){
return **string based on private fields**
}
}
}
Then I extend this...
public class ApplePie extends Pie{
protected Slice[] slices;
// Apple Pie constructor
public ApplePie(int n){
super(n);
}
// Inner class...
public class Slice extends Pie.Slice{
public Slice(float startAngle){
super(startAngle);
//set some **additional** private fields based on startAngle **specific to apple pie** appleness or something
}
#Override
public String toString(){
return **string based on apple pie specific private fields**
}
}
}
Now, when I make an Apple pie and call its toString method, like so...
ApplePie ap = new ApplePie(8);
System.out.println(ap.toString());
I do not get information about the apple pie slices, but information about the pie slices. It ignores my toString override, or more likely ignores my apple pie Slice. How can I arrange it such that apple pie slices refer to ApplePie?
Any help much appreciated! Sorry for pie references - it is the actual class I am working with...
I've changed your code to meet your requirements.
Your super class Pie is about to create a new instance of Slice, but the child class ApplePie's Slice does not override the Slice method of its super class'.
I added the functions below to enable the child class to create its own Slice.
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
Pie.java:
public class Pie {
private int a = 1;
protected Slice[] slices;
// Pie constructor
public Pie(int n) {
sliceGenerator(n);
}
private void sliceGenerator(int n) {
newSliceArray(n);
final float sweepAngle = 360.0f / n;
float startAngle = 0;
for (int i = 0; i < n; i++) {
slices[i] = newSlice(startAngle);
startAngle += sweepAngle;
}
}
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
#Override
public String toString() {
String t = "";
for (Slice s : slices) {
t += s.toString();
}
return t;
}
// Inner class...
public class Slice {
public Slice(float startAngle) {
// set some private fields based on startAngle and generic pie
}
#Override
public String toString() {
return "" + a;
}
}
}
ApplePie.java:
public class ApplePie extends Pie {
private int b = 2;
// protected Slice[] slices;
// Apple Pie constructor
public ApplePie(int n) {
super(n);
}
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
// Inner class...
public class Slice extends Pie.Slice {
public Slice(float startAngle) {
super(startAngle);
// set some **additional** private fields based on startAngle **specific to apple pie**
// appleness or something
}
#Override
public String toString() {
return b + "";
}
}
}
Test:
public static void main(String[] args) {
ApplePie ap = new ApplePie(8);
System.out.println(ap.toString());
}
The code will print 22222222
In your superclass, you are creating and storing Pie.Slice objects:
private void sliceGenerator(int n){
slices = new Slice[n];
final float sweepAngle = 360.0f/(float)n;
float startAngle = 0;
for (int i=0;i<n;i++){
slices[i] = new Slice(startAngle);
startAngle += sweepAngle;
}
}
These are the same objects being used by Pie.toString (which ApplePie doesn't override by the way).
Extending Pie with ApplePie and extending Pie.Slice with ApplePie.Slice doesn't change this. The new Slice(startAngle) in the above code does not magically switch to instantiating something different.
Aside from that, your Pie.toString() isn't returning anything - it shouldn't even compile:
#Override
public String toString(){
for (Slice s:slices){
s.toString();
}
}
I'm guessing you want to return a String representing all the slices. This would be a quick solution for example:
#Override
public String toString() {
return Arrays.toString(slices);
}
(Arrays.toString is just a utility method to get a String representing of an array.)
The answer lies within your program. When you instantiate Slice class, it gives call to the super class and invokes sliceGenerator. This method internally creates instances of Pie.Slice and not ApplePie.Slice. To get around this, make sliceGenerator method protected and override it in Apple.Slice class. Create the instances of Apple.Slice and it should work.