How these codes work (Constructor And ListView) - java

I was following the udemy android app development course, In the course, we were writing code to Create A listview and get some data when the user clicks on the list, to do that the teacher uses a thing called Constructor I know how constructors work theoretically but can't understand the way it works in code. It will be great if someone can explain what these lines of codes do.
edit: Full Code is here https://github.com/atilsamancioglu/A14-LandmarkBook
import android.graphics.Bitmap;
public class Globals {
private static Globals instance;
private Bitmap chosenImage;
private Globals(){
}
public void setData(Bitmap chosenImage){
this.chosenImage=chosenImage;
}
public Bitmap getData(){
return this.chosenImage;
}
public static Globals getInstance() {
if(instance==null){
instance = new Globals();
}
return instance;
}
}

Constructors are special methods invoked when an object is created and are used to initialize them.
A constructor can be used to provide initial values for object attributes.
You can think of constructors as methods that will set up your class by default, so you don’t need to repeat the same code every time.
In your codes, you can define the constructor as below(it may be unrelated, it's just an example):
private Globals(int id){
return chosenImage.setId(id);
}
The constructor is called when you create an object using the new keyword:
Globals objectGlobe = new Globals(000008);
Also a single class can have multiple constructors with different numbers of parameters.
The setter methods inside the constructors can be used to set the attribute values.
It's not bad to be mentioned that; Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.

Related

Java Application return super class when initialized

Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.

Accessing variables of the wrapper object in OOP

I am creating an application in VBA for my employer (and a similar one in Java for hobby purposes) and its purpose is to 'contain' different tools that will help in our daily work. It's going to be some kind of platform with the main app window and from there a user can access some of the application components like for instance a sub-program when a user can give me feedback on application's functionality, then the info will be stored in a database that I can access later.
I already have a structure: an Application class, that contains the Application Manager and this one class contain an array of fields of the SubApp type. A SubApp type contains view, logic, and business of a sub-application. The Application class also contains members like the name of the app and the information about the user that is currently using the app (previously accessed from the application database).
Whenever a sub-app launch, I would like to put on the title bar the name of the app as well as the name of the sub-app, something like application_name - sub_app_name. The problem is, that I have no idea how can I access it the 'right way'. Recently I've achieved this by creating the app variable as a global object, then accessing it is no problem using some getters. I feel however that storing an application variable as a global variable is a bad practice.
The same problem occurs with the member variable storing info about the current user. I'd like to store the information about the current user while he's giving feedback (tool for giving a feedback is a sub-app in my application)
So here is my question: how can I access the methods/variables of a wrapping object from within one of the member methods/variables?
Any suggestions regarding the overall design of the application would also be welcome.
Object oriented design: use getters and setters for all fields is proper practice. If you want to be lazy, make all your fields public and they will be accessible from the object without getters or setters.
If you wish to access a variable throughout multiple methods in a class.
A) You'll can make a variable global
B) Create a local variable, and pass it as a parameter until you no longer need to use it.
public class Main { //All implementations stated above
private Object globalObject;
public static void main(String[] args) {
Object localObject;
method1(localObject);
method2ThatUsesGlobalObject();
}
}
Accessing variables between classes:
A) Make a variable static
B) Pass it through method parameters, or constructor parameters
C) Use abstract classes or interfaces
Here are examples of the code usage I've stated
public abstract class JavaAbstractClass {
public abstract Object giveMeThisObjectWhenINeedItThanks();
}
public interface JavaInterface {
Object giveMeThisObjectWhenINeedItThanks();
}
public class Main { //All implementations stated above
public static Object object; //Accessible by Main.object everywhere
public static void main(String[] args) {
Object local;
ClassOne class = new ClassOne();
class.method1(local);
new ClassWithInterface() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
new JavaAbstractClass() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
}
}

Best way to pass arguments in constructor

I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.
just example:
class RowWidget extends FlexTable{
public static void initWidget(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment)
{
// ...
}
}
Then I called below constructor for each record data.
public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
// ...
}
As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like
public RowWidget(DataRawType dataRawType,
Data data,
Data parentData,
Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) {
// ...
}
But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.
Is Anyone suggest me:
How to construct class which have same property required in another
instance?
Note:I know this is possible through static only but don't want to use static.
What is best way to construct class with having some default fix
property for all instances?
Note: I don't want to create another class to achieve it. or any getter/setter method.
Thanks In advance.
I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:
RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();
Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164
Why not create method which will accept the newValues for the properties you want to change & return a new instance of the classes with all other properties copied from the instance on which you invoked this method.
You could separate/extract the parameters from the RowWidget-class fro example in a RowWidgetConfig-class.
class RowWidgetConfig {
// put here all your parameters that you need to initialize only once
// init using setters
}
Now create once instance of that class and pass it among the other parameters to RowWidget constructor.
Another alternative would be to have factory for creating RowWidget instances. The factory would also contain all the parameters you need for a row instance plus a factory method createNewRowWidget witch creates an instance base on the parameters contained in the factory.
class RowWidgetFactory {
// put here all your parameters that you need to initialize only once
// init using setters
public RowWidget createNewRowWidget() {
// create
return ...
}
}
How to construct class which have same property required in another instance?
To achive this you can have a super class with all the properties you want. So any class extending this super class will be have these properties. This way you don't need to use static keyword.
What is best way to construct class with having some default fix property for all instances?
For this one you can have an interface with some constant properties. This way any class implementing this interface will be having the fixed properties.
The static initWidget() thing just doesn't seem right for me. Though probably now you will only have one set of RowWidgets which share some properties, it is also reasonable to have 2 sets of RowWidgets, each set will have its own "shared" properties. Things will be much more fluent and you have much more choices in building more reasonable APIs if you refactor your code to make a more reasonable design
Assume now I introduce something like a RowGroup (which kind of represents the "shared" thing you mentioned)
(Honestly I don't quite get the meaning for your design, I am just making it up base on your code);
public class RowGroup {
public RowGroup(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) { .... }
public void addRow(DataRawType dataRawType, Data data, Data parentData) {...}
}
When people use, it looks something like:
RowGroup rowGroup = new RowGroup(form, permissionMap, gridMode, isApplied, isChildExist, isChildAttach);
rowGroup.addRow(DataRawType.A, dataA, parentA);
rowGroup.addRow(DataRawType.B, dataB, parentB);
You may even provide builder-like syntax or a lot other choices.
RowGroup rowGroup
= new RowGroup(.....)
.addRow(DataRawType.A, dataA, parentA)
.addRow(DataRawType.B, dataB, parentB);
Even more important, the design now make more sense to me.
If you did not want to create another class, I'd suggest what A4L suggested.
Without creating another class, I would create constructor that takes all parameters and factory method that uses current instance as template and pass its own parameters to constructor parameter.
example (with obvious parts ommited)
class A{
public A(int p1, int p2){...}
public A create(int p2) {
return new A(this.p1,p2);
}

Doing an API, constructor for system private use only and another official, javadoc'ed and public to use. Advise on fix / pattern approach

I guess this is a bad pattern, whats the best approach to fix it?
I mean I would like everybody using a constructor with 2 arguments,but I need to leave default constructor because its implementing a listener which classloads it without args. I would like to hide default constructor to anyone else but the listener handler which uses it, and make the other the unique point to instantiate.
Is there any kind of annotation? any privacy modifier for certain classes (system caller one is not in the same package)?
This seems fine to me. You would do the same thing if you want to instantiate a class differently during unit testing.
Oh, I see you need a constructor that has more access than protected but less than public. Unfortunately that's not possible.
You could put both your class MyClass and the listener MyListener that needs to use the empty constructor in the same package. Then, set the access of the empty constructor to package-level:
package com.stackoverflow.foo;
public class MyClass {
MyClass () { // package-private (no explicit access modifier)
}
public MyClass(int a, int b) { // public
}
}
package com.stackoverflow.foo;
public class MyListener {
private MyClass ref = new MyClass(); // MyListener is on the same package as MyClass, so this is valid
}
This way, you ensure that only classes that are on the same package as MyClass can use the default constructor.

final static String defined in an interface not evaluated at compile time - Android

I have two classes and an interface (for example DatabaseModel, LocalStore, and InternalModelInterface). They're defined as follows;
public class DatabaseModel {
// ...
public static final String KEY_PARAM1 = "param1";
}
public class LocalStore implements InternalModelInterface {
// ...
public void function () {
String temp = InternalModelInterface.COLUMN_PARAM1;
}
}
public interface InternalModelInterface {
public static final String COLUMN_PARAM1 = DatabaseModel.KEY_PARAM1;
// ...
}
The issue I'm experiencing is that at runtime, when I call localStore.function(), temp is being assigned null, as InternalModelInterface.COLUMN_PARAM1 is null. Does this make sense? Shouldn't InternalModelInterface.COLUMN_PARAM1 be evaluated at compile time and inlined?
This is for an Android application. Thanks in advance.
I'll further explain to clarify any confusion.
Objects of the DatabaseModel class are instantiated as a JSON response is parsed. The constants defined in the DatabaseModel class represent the keys to look for in the JSON response.
The InternalModelInterface defines the column names used in the local (cache) database on the device. For several reasons (including they keys being illegal column names in SQLite), I'm not reusing the keys as column names.
The reason I'm using an interface and not just a plain class is that the interface also specifies required methods that need to be implemented by the third class, LocalStore.
JLS3 §8.3.2.1, §9.3.1 http://java.sun.com/docs/books/jls/third_edition/html/classes.html#38010
at run time, static variables that are
final and that are initialized with
compile-time constant values are
initialized first. This also applies
to such fields in interfaces (§9.3.1).
These variables are "constants" that
will never be observed to have their
default initial values (§4.12.5), even
by devious programs.
So null should never be observed in your example. It's an Android bug then.
I'm not and android expert but I think that if you don't create an instance of the class, it's optimised out at compile time. If you create a constructor for DatabaseModel and instantiate it somewhere it seems to solve this for me.

Categories

Resources