Abstract vs No instance approach? - java

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 "";
}
}

Related

What is wrong with class?

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;
}
}

JAVA Inheriting static field from base class in the way that it will differ for every subclass

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.

Static parameter with different values in subclasses

I want to create a solution for the following problem without much redundancy:
I have an abstract class Unit, subclasses SubUnit1 and SubUnit2. All Units have a maxValue, which differs from SubUnit1 to SubUnit2, but should be the same for all instances of the same sub unit at any time.
I don't want to copy all the setters, getters or some kind of method around these values, because they are identical for all subclasses. I also don't want to use normal paramters and hand down the methods to subclasses and update every single instance of these subclasses if necessary. And somehow get the current value when I create a new instance.
Is there a way to declare some sort of static parameter and methods in the parent class Unit, that differ in the different subclasses?
You could define a protected constructor in the parent class that accepts the value of the MAXVALUE
public abstract class Unit {
private final int maximum;
protected Unit(int maximum) {
this.maximum = maximum;
}
public int getMaximum() {
return maximum;
}
}
Then in your derived classes you expose constructors that call the parent's constructor with a fixed value, unique per subclass.
public class SubUnit1 {
private static final int SUBUNIT1_MAX = 10;
public SubUnit1() {
super(SUBUNIT1_MAX);
}
}
No, but using an interface you may express that a UNIT should have a MAXVALUE.
public interface IUnit
{
public int getMaxValue();
}
public class SubUnit implements IUnit
{
private static final int MAX_VALUE = 48;
#Override
public int getMaxValue() {
return MAX_VALUE;
}
}

How to create a class which is not inheritable and static in java?

Can you please help me how to create a class which is not inheritable and should be static in behavior (Means we should not be able to create instance of it). I need this class to store constant values. Thanks.
public final class MyClass {
private MyClass() { }
}
The final keyword makes it not inheritable, and making the constructor(s) private will help stopping it from being instantiated.
you can use final keyword to class can not be inherited.
But I would recommend you to Use Enums. Enums can not be inherited and only one instance exists per constant value. Also you can do lot more with enums.
public enum DaysOfweek
{
SUNDAY,MONDAY.....
}
You can read more about Enums here Enum Types
Why not use an interface which has a couple of static and final variables?
For the first case, you can use final class as they can't be inherited..
For your second case, you can use interface, they are very well used to store Constants.
But you cannot have both of them together (As having an interface which cannot be implemented does not make sense)..
So, the best is you can mix the property of both in one class.. You can have a final class with public static final variables, as this is what makes a variable constant in interface, will serve the purpose of constants..
public final class A {
public static final int YOUR_CONST = 5;
}
If you don't want to make instance of this class, you can have a private 0-arg constructor in it..
public final class A {
public static final int YOUR_CONST = 5;
private A() {}
}
Declare it as final which will not allow other classes to extend it, and make its constructors private so no one else (except your own class) will be able to instantiate it:
public final class MyClass {
private MyClass() {
// Private so noone else can instantiate this
}
}
Below is an example of the class to contain a constant value:
public final class Trial // it is the FINAL
{
private static final int CONSTANT_VALUE = 666;
private Trial() // it is PRIVATE instead of PUBLIC
{
}
public static int getConstantValue()
{
return CONSTANT_VALUE;
}
}
And below is an example of how to test the above class:
public class Bully //extends Trial ////"extends" WILL NOT COMPILE
{
public static void main(String[] args)
{
//Trial trial = new Trial(); ////"new Trial()" WILL NOT COMPILE
// The only thing can be done is getting a constant value from "Trial"
int acquiredValue = Trial.getConstantValue();
System.out.println(acquiredValue);
}
}
Hope that helps :))
public final class MyClass {
public static string MY_STRING;
public static int MY_INT;
private MyClass() {}
}
final : Make a class final that means this class can not be inherite further more.
static : If all methods are static the you do not need to create instance of this class. and should be static in behavior.
Singleton pattern : If your all methods are not static and you do not want to create more than one instance then you can make constructor private and keep one variable of class object in the class. And create once if it is null, and if not null then return same instance always.
Thanks

Implement a final class without the "final" keyword

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

Categories

Resources