I'm a beginner when it comes to programming Java code. I'm having a real tough time on how this class is wrong such as when I'm trying to extend the class. public final class SeatType extends Enum
This is my whole class:
package assignment;
public final class SeatType extends Enum
{
public static final SeatType AISLE;
public static final SeatType WINDOW;
public static final SeatType MIDDLE;
private static final SeatType $VALUES[];
public static SeatType[] values()
{
return (SeatType[])$VALUES.clone();
}
public static SeatType valueOf(String name)
{
return (SeatType)Enum.valueOf(assignment/SeatType, name);
}
private SeatType(String s, int i)
{
super(s, i);
}
static
{
AISLE = new SeatType("AISLE", 0);
WINDOW = new SeatType("WINDOW", 1);
MIDDLE = new SeatType("MIDDLE", 2);
$VALUES = (new SeatType[] {
AISLE, WINDOW, MIDDLE
});
}
}
EDIT:
These are the errors.
SeatType cannot be resolved to a variable. assignment cannot be
resolved to a variable. The type SeatType may not subclass Enum
explicitly. The constructor Object(String, int) is undefined –
Any help is much appreciated :)
In Java , it wont allow you to extend Enum explicitly.
You can create an enum like below :
public enum Season {
WINTER, SPRING, SUMMER, FALL;
}
According to the Java Language Specification, Each enum is implicitly final and is a subclass of Enum. So an enum already inherits from another class, making it a subclass of another class would break Java's single inheritance paradigm. An enum can, however, implement an interface
Why are you extending Enum? In Java you cannot do this. If you want to create an enumeration class you should create a class with the definition
public enum SeatType {
// your enum code
}
Your class is wrong because you're extending the Enum class.
You cannot extend from Enum. You declare an Enum class like that:
public enum MyEnum {
AISLE,
WINDOW,
MIDDLE;
}
That will create your Enum. The actual usage will look like that:
MyEnum.valueOf("AISLE");
MyEnum.AISLE;
Java compiler doesn't allow you to extend ENUM class. Have a look at this answer.
Also, please read this to learn about using enum.
In this case, you can create an enum like,
public enum SeatType
{
WINDOW, AISLE, MIDDLE
}
You don't need to extend Enum at all. You just need to use the enum keyword to declare an enum:
enum SeatType {
...
}
You don't need to have values and valueOf methods. They are inherited from Enum.
From the looks of it, your enum seem to have 2 fields - i and s. You should declare them as fields:
int i;
String s;
Then, write a constructor that takes an int and a string that assigns the parameters to the fields:
SeatType(String s, int i) {
this.i = i;
this.s = s;
}
Then, you can declare your enum values:
AISLE("AISLE", 0),
MIDDLE("MIDDLE", 1),
WINDOW("WINDOW", 2)
;
So your whole enum looks like this:
enum SeatType {
AISLE("AISLE", 0),
MIDDLE("MIDDLE", 1),
WINDOW("WINDOW", 2)
;
int i;
String s;
SeatType(String s, int i) {
this.i = i;
this.s = s;
}
}
Related
I have a super class named TestSuper
public class TestSuper {
int a = 0;
}
and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper
public class TestSub extends TestSuper{
int a=1;
}
public class TestSub2 extends TestSuper{
int a=2;
}
in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console
public class Main {
public static void main(String[] args){
System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
return b.a;
}
}
but the output is "0 0" instead of "1 2", what do I do?
You need to cast the reference so say which one you want.
public static int test(TestSuper b){
return b instanceof TestSub ? ((TestSub) b).a :
b instanceof TestSub2 ? ((TestSub2) b).a :
b.a;
}
If this seems needlessly complicated, it is. You should use polymorphism instead.
public class TestSuper {
int a = 0;
public int getA() { return a; }
}
public class TestSub extends TestSuper {
int a = 1;
public int getA() { return a; }
}
public class TestSub2 extends TestSuper {
int a = 2;
public int getA() { return a; }
}
public static int test(TestSuper b) {
return b.getA();
}
First understand the difference between hiding and overriding: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Then create a getter method in the base-class which you can override in the subclass.
You can look into the theory behind this, and then do the only reasonable thing -forget about writing such kind of code.
In good OOP you consider your fields to be part of your "secret" internal implementation. You don't use fields of sub classes in the super class context. Period.
You are even very conservative about making a field protected in the superclass and to use that in subclasses.
When you call test method like this:
test(new TestSub())+" "+test(new TestSub2())
You use upcasting. Upcasting seperates interface and implementation for an object. But for seperating interface and implementation and achieving true implementation in polymorphism, you must use polymorphic structures. The instance variables aren't polymorphic. Because of this, actually you call a variable which is in TestSuper class.
Only instance methods are polymorphic.
I have one class (class util) for generating password(it has only one public static method ). Here two ways are : To make it abstract so no one can create its instance
public abstract class PasswordGenerator {
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
or to make its constructor private. So What's the best approach to do that ?
public class PasswordGenerator {
private PasswordGenerator() {
}
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
So What's the best approach to do that ?
You should definitely not make the class abstract, as this might indicate to other developers, that it is intended to be extended (and therefor instantiated).
Having a class technically being able to be instantiated is a minor problem.
But in this SO thread you can see a workaround, that uses a private constructor in combination with making the class final.
Make both the class final and the constructor private.
With the final keyword you clearly express the intent that the class is not made to be inherited.
With the private constructor you clearly express the intent that the class is not made to be instanciated.
public final class PasswordGenerator {
private PasswordGenerator() {}
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
I have a base class
public class base
{
//some stuff
}
and several subclasses
public class sub1 extends base
{
static int variable;
}
public class sub2 extends base
{
static int variable;
}
etc
The static int variable exists in every subclass because I store in it information that is characteristic for every subclass. But it would be better if there was a way to move static int variable to base class in the way that it still will be different for every subclass.
In the way that it is now I am repeating myself, when adding some another subclass, it's a bad practice.
So anyone has some idea how to acomplish this? Maybe there's a design pattern that fits to this situation?
You cannot move all the different static variables from derived classes into the base class, because static variables are one-per-class; you want your variables to be one-per-subclass, which is not allowed.
You could work around this issue by defining a registry of subclasses in your base class, and store the int for each subclass there. However, this would add a lot more complexity, and it is not clear how you would differentiate between subclasses in the superclass.
Your current solution appears optimal.
Don't use a static field for this - that's not the way to go, because static fields of a subclass do not "override" those of a super class.
Instead, because the values are constant for a given class, use a final instance field:
public class Base {
protected final int variable;
public Base() {
this(5);
}
protected Base(int v) {
variable = v;
}
}
public class Sub1 extends Base {
private static int v = 7;
public Sub1() {
super(v);
}
}
Now the variable is fixed and accessible to all instances.
You can certainly move variable into the base class, but it cannot be static. Alternatively, you can make static getters which you override in each subclass. Here is an example of both:
public class base {
protected int variable;
protected static int getVariable() {
return -1;
}
}
public class Sub1 extends base {
public Base() {
variable = 0;
}
protected static int getVariable() {
return 0;
}
}
public class Sub2 extends base {
public Sub2() {
variable = 1;
}
protected static int getVariable() {
return 1;
}
}
As a design principle, it is somewhat rare (in my opinion) that you genuinely want static methods. Usually you will have some instance of the class around that you are working with. If you want a whole bunch of objects to share some common behavior which you configure at runtime, you might want to check out the flyweight pattern.
Suppose I have a class that contains an enum in Java. Is it possible to access methods from the class that the enum is contained in? As an example:
public class Foo {
private string getClassVal() { return "42"; }
public string getOtherClassVal() { return "TheAnswer"; }
public enum Things {
ONE("One"),
TWO("Two"),
THREE("Three");
private String _val;
private Things(String val) { _val = val; }
// This method is the problem
public String getSomeVal() {
return _val + this.getClassVal();
}
// And this one doesn't work either
public String getSomeOtherVal() {
return _val + this.getOtherClassVal();
}
}
I know the enum methods above with comments do not work and result in errors, because of the context that this is in. What I'm looking for is something where I can access the "outer" class methods from within the enum. Or is this even the correct approach?
Is something like this possible? Or are enums locked up to outside methods, even within a class?
No.
Because enums are always static and therefore have no enclosing instance.
Obviously they CAN access public static methods of the enclosing class.
A friend of mine was asked that question in his on-phone job interview a couple of days a go.
I don't have a clue. can anyone suggest a solution?
(His job interview is over. just out of curiosity now )
10x.
Mark constructor as private
Provide a static method on the class to create instance of a class. This will allow you to instantiate objects of that class
I don't know what they mean exactly mean by a final class. If they mean a class that cannot be extended by inheritence, than clearly this cannot be done, except by marking that class with final (or sealed, or whatever the language keyword is).
But if the mean final as in immutable, such that a derived class can't modify the value of the fields in the class,than the base class should have all of the fileds and accessor methods private.
Create a private constructor without parameters?
public class Base
{
private Base()
{
}
}
public class Derived : Base
{
//Cannot access private constructor here error
}
Make all the constructors of that class as private to stop inheriting, Though not recommended.
public class Immutable {
private int val;
public Immutable(int v)
{
this.val = v;
}
public int getVal() { return this.val; }
}
You can make your class immutable without using final keyword as:
Make instance variable as private.
Make constructor private.
Create a factory method which will return the instance of this class.
I am providing immutable class here in Java.
class Immutable {
private int i;
private Immutable(int i){
this.i = i;
}
public static Immutable createInstance(int i){
return new Immutable(i);
}
public int getI(){return i;}
}
class Main {
public static void main(string args[]){
Immutable obj = Immutable.createInstance(5);
}
}
Static classes can't be inherited from