I want to use Constructor Overloading in my class and I also would like to have some final variables to define.
The structure I would like to have is this:
public class MyClass{
private final int variable;
public MyClass(){
/* some code and
other final variable declaration */
variable = 0;
}
public MyClass(int value){
this();
variable = value;
}
}
I would like to call this() to avoid to rewrite the code in my first constructor but I have already defined the final variable so this give a compilation error.
The most convenient solution I have in mind is to avoid the final keyword but of course it is the worst solution.
What can be the best way to define the variable in multiple constructors and avoid code repetitions?
You are almost there. Rewrite your constructors such way that your default constructor call the overloaded constructor with value 0.
public class MyClass {
private final int variable;
public MyClass() {
this(0);
}
public MyClass(int value) {
variable = value;
}
}
If you have small number variable then it is ok to use Telescoping Constructor pattern.
MyClass() { ... }
MyClass(int value1) { ... }
Pizza(int value1, int value2,int value3) { ... }
If there is multiple variable and instead of using method overloading you can use builder pattern so you can make all variable final and will build object gradually.
public class Employee {
private final int id;
private final String name;
private Employee(String name) {
super();
this.id = generateId();
this.name = name;
}
private int generateId() {
// Generate an id with some mechanism
int id = 0;
return id;
}
static public class Builder {
private int id;
private String name;
public Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Employee build() {
Employee emp = new Employee(name);
return emp;
}
}
}
You can not assign final variable in both constructors. If you want to keep the final variable and also want to set via constructor then one possibility that you will dedicate one constructor to set the final variable and also include common code functionality needed by the class. Then call this from another constructor like this(*finalVariableValue*);
Related
I want to have Classes extending a Superclass where only the Variables differ, the Methods stay the same. This is for an example of a Decorator Pattern. The Superclass implements an Interface, which forces the Methods to be overridden, but the Methods require variables that should be changed. The Code is the Following:
interface wearable{
int getItemColdResistance();
String getItemName();
}
abstract class BaseWearable implements wearable{
boolean addsColdResistance = true; //This is just because I need an Example of a Base-Decorator
}
class Underwear extends BaseWearable{
String name = "Underwear";
int itemColdResistance = 1;
#Override
public String getItemName() {
return name;
}
#Override
public int getItemColdResistance() {
return itemColdResistance;
}
}
class Shirt extends BaseWearable{
String name = "Shirt";
int itemColdResistance = 2;
#Override
public String getItemName() {
return name;
}
#Override
public int getItemColdResistance() {
return itemColdResistance;
}
}
So the Variables name and itemCodeResistance differ and must be defined in each Subclass, but the Methods stay exactly the same. How can I write general Methods in the Superclass and change the Variables needed in those Methods in the Subclasses? Is that even possible?
Looks like you want something like that:
interface Wearable{
int getItemColdResistance();
String getItemName();
}
abstract class BaseWearable implements Wearable{
boolean addsColdResistance = true; //This is just because I need an Example of a Base-Decorator
private String name;
private int itemColdResistance;
BaseWearable(String name, int itemColdResistance) {
this.name=name;
this.itemColdResistance = itemColdResistance;
}
#Override
public String getItemName() {
return name;
}
#Override
public int getItemColdResistance() {
return itemColdResistance;
}
}
class Underwear extends BaseWearable{
Underwear() {
super("Underwear",1);
}
}
class Shirt extends BaseWearable{
Shirt() {
super("Underwear",2);
}
}
BTW: The interface name should start with uppercase character
No it is not possible.
But it is not at all clear why you need different variables and don't just set the variables to different values.
There is no way.
Neither should there be. The variables are not part of the visible interface. (Or rather: Should never be.)
In a project I want, Getter and Setter methods for all the member variables. how can i do this? and what does this mean?
the following is the code where i want to use getter and setter method
public abstract class Connection {
int previousReading;
int currentReading;
float[] slabs;
public Connection(int currentReading, int previousReading,float slabs[])
{
this.currentReading = currentReading;
this.previousReading = previousReading;
this.slabs = slabs;
}
public abstract float computeBill();
}
In order to achieve the desired design, you need to follow the Encapsulation concept (also known as 'Data hiding'), which is one of the basic OOP concepts.
What Encapsulation means is basically, wrapping the variables in accessors methods (called getters and setters) in order for them to be hidden from other classes.
The variables can be accessed only through those getters and setters and not directly.
In order to achieve this:
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the
variables values.
Example:
public class Person {
private String name;
private int age;
public String getName() {
return this.name;
}
public String setName(final String name) {
this.name = name;
}
public String getAge() {
return this.age;
}
public String setAge(final String age) {
this.age = age;
}
}
Why do we need Encapsulation for?
Using Encapsulation we can:
Control the allowed accessors of a variable (by declaring the access level as protected/public).
Limit the values that can be stored in a field.
Perform an action when a field is modified (perform validation, trigger an event, call another method).
Change the data representation (convert the input data type).
Provide thread safety using synchronization.
public class Connection {
private int previousReading;
private int currentReading;
private float[] slabs;
public Connection(int currentReading, int previousReading,float slabs[])
{
this.currentReading = currentReading;
this.previousReading = previousReading;
this.slabs = slabs;
}
public int getPreviousReading() {
return previousReading;
}
public void setPreviousReading(int previousReading) {
this.previousReading = previousReading;
}
public int getCurrentReading() {
return currentReading;
}
public void setCurrentReading(int currentReading) {
this.currentReading = currentReading;
}
public float[] getSlabs() {
return slabs;
}
public void setSlabs(float[] slabs) {
this.slabs = slabs;
}
}
I have a variable in x class .And I have another class called "Y" to access the variable. Will it change the value in X class, if the value is incremented in Y class?
Java uses pass by value but we can achieve what you are asking for by passing an object as an argument to a method like this:
public class ClassX {
public int classId;
public ClassX(int id) {
this.classId = id;
}
public void setId(int id) {
classId = id;
}
public int getId() {
return classId;
}
}
public class ClassY {
public static void main(String[] args) {
ClassX cx = new ClassX(100);
ClassY cy = new ClassY();
System.out.println("classId:"+cx.classId);
cy.modifyId(cx); // an object is passed as argument to a method
System.out.println("classId:"+cx.classId);
}
public void modifyId(ClassX classx) {
classx.setId(220);
}
}
Assuming you have it defined like
public int anInteger = 4;
Then yes, it would change.
These are the sorts of things best learned from experimentation, try various ways of structuring the classes, declaring the variable, and accessing it. See what happens.
Yes. All you need is to pass a reference to it to the other class.
I'm trying to share variables between methods in different classes, but I don't know if I'm doing this in the correct way. Basically when I wanna use the variables on method2 I have to "transport" them throught method1 to method2 from the Class A, just take a look at the example because I don't know how to explain this properly.
Is this the correct way to do it? Because sometimes I do this over an over through methods and it looks ugly.
Example:
public class A {
int var1, var2, var3;
B b = new B();
b.method1(var1, var2, var3);
}
public class B {
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
public void method2(int var2, int var3){
//doSomething
}
}
Btw, is there any community where code reviews are done? I'm pretty new to code and I'm afraid that I'm creating code that isn't effective.
Thanks for the help! :)
Use getters and setters to get variable of Class A from B as following..
public class A {
private int var1, var2, var3;
public int getVar1(){
return var1;
}
public void setVar1(int var1){
this.var1 = var1;
}
public int getVar2(){
return var2;
}
public void setVar2(int var2){
this.var2 = var2;
}
public int getVar3(){
return var3;
}
public void setVar3(int var3){
this.var3 = var3;
}
}
public class B{
// Use var 1 from class A as following
A a = new A();
int x = a.getVar1(); //x has the value of Var1 now
a.setVar1(2); // var1 in class A has value 2 now.
}
Use interfaces rather than directly call a method of another class.
public class A {
private InterfaceB interfaceB;
interfaceB.method1(var1, var2, var3);
}
public interface InterfaceB{
public void method1(int var1, int var2, int var3);
public void method2(int var2, int var3);
}
public class B implements InterfaceB{
#Override
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
#Override
public void method2(int var2, int var3){
//doSomething
}
}
You should read about encapsulation.
Passing 3 variables encapsulated in 1 object with appriopriate accessors sounds like a better option to me (at least the code looks a bit cleaner).
Also, think of creating a utility class with static methods if it makes sense of course - sometimes you do not need class member fields at all because there is no state to this class (Math class is an example) and static methods that return the result of some calculation/transformation is a better option.
On a side note I can recommend you considering "Program to an interfaces" principle. You can read the relevant section right on the top of this page.
In B class, you declare a instance of A class, variables in A class is public. when you can use variable in A class.
Here is my 2 cents...
public class Sample {
//Property of the class
private int valueA;
//method to do some operation
//that relies explicitly on a
//property of the class
public void doSomething(){
//valueA is over 9000!?
int valueA = valueA + 9000;
}
//Method that does something that does not explicitly
//rely on a property of the class
//could be called from this or another class
public int doSomeOperationWithSomething(int something){
return something++;
}
}
Another alternative would be to create a static "utility" class for your methods
public class Utils{
public static int doMagic(int var){
return var * var;
}
}
used like this,
int num = Utils.doMagic(9);
These come about when you have some code that does that one useful thing, but you just can't figure out where to put it.
More importantly, you will want to maintain proper "encapsulation" (Read about that) in your code. This means limiting access to variables by other classes and allowing access to only what is needed.
public class Website {
//No one should ever be able to
//access this variable directly
//So we set it a private
private String article;
//A reader should be able to get the aricle
public String getArticle(){
return article;
}
//The reader should never be able to set
//an aticle on the website only read it
//You can leave this part out or
//set the method to private as i did.
private void setArticle(String article){
this.article = article;
}
}
public class Reader {
//Reference to website
private Website website;
public Reader(){
...
//the user can read an article
website.getArticle();
// but this is not available to them
website.setArticle("Some text"); // results in ERROR
}
}
I have two classes:
class a {
public static int var;
private int getVar() {
return var; //Yes
}
private void setVar(int var) {
a.var = var; //Yes
}
}
class b {
private int getVar() {
return a.var; //Yes
}
private void setVar(int var) {
a.var = var; //No
}
}
Q: Can i make modifiable member only from his class, for other classes would be constant ?
No, the public access modifier basically allows you to modify the value of the reference from anywhere in your code base.
What you can do is have a private or less-restricted access modifier according to your specific needs, and then implement a getter, but no setter.
In the latter case, remember to add some logic to prevent mutable objects, such as collections, from being mutated.
Example
class Foo {
// primitive, immutable
private int theInt = 42;
public int getTheInt() {
return theInt;
}
// Object, immutable
private String theString = "42";
public String getTheString() {
return theString;
}
// mutable!
private StringBuilder theSB = new StringBuilder("42");
public StringBuilder getTheSB() {
// wrapping around
return new StringBuilder(theSB);
}
// mutable!
// java 7+ diamond syntax here
private Map<String, String> theMap = new HashMap<>();
{
theMap.put("the answer is", "42");
}
public Map<String, String> getTheMap() {
// will throw UnsupportedOperationException if you
// attempt to mutate through the getter
return Collections.unmodifiableMap(theMap);
}
// etc.
}
Just remove setter and make variable private. Then other class only can read the value stetted.
public class a {
private static int var=2;
public static int getVar() {
return var;
}
}
But when you come to Java reflection there is no such protection.
The answer Is NO you can't make a public static variable only modified from its class you can make the variable private and has only public getter or you can add setter private