Use instance variable in conjunction with objects - java

Greetings fellow programmers!
So I've been learning java for 2 months and its been a really awesome experience and journey. There's a confusing thing in java I still don't know why I can do it. The idea is using using instance variable in conjunction with objects.
How come I can specific the objectname.instance variable associated with the object? What's this process called?

It's called dereferencing, the same as calling a method via objectname.method(). Note that strictly speaking, it's not the object's name, but the name of the reference (there can be many references with different names refering to the same object).
Note also, that it's considered better to encapsulate instance variables by making them private and providing set/get methods if necessary.

That'd be dereferencing, I believe. It's not as explicit in Java as in languages that confront you with concepts like pointers or memory offsets.

Related

How can you give an object a value in android studio?

I am new to programming. I cannot understand most of oop. I am trying to make a custom array adapter, but I do not understand how can you assign a value to an object for example: LayoutInflater myinflater= LayoutInflater.from(getContext()); I always thought that when creating an object you use it just for the methods the class has and to call its constructor LayoutInflator myinflator = new LayoutInflator();
I hate memorizing something I do not understand and end up looking at every class that is used in tutorials but end up getting more confused. Can someone please also tell me the best way of learning Android Studio for beginners.
There are two types of classes (instantiable and static -- instantiable is the default, so there's no keyword associated). Instantiable classes can be instantiated, with new Classname(constructor,arguments,here). Static classes can't be instantiated, and usually refer to something that simply exists in the programmer's conceptual space of the program. (For example, on desktop computers, programs have an Environment that contains variables that can be set in memory before the program is started. Since there's only one Environment, it is a static class.)
There are also two types of methods (instance and static -- again, instance is the default, so there's no keyword associated). Instance methods act on data associated with an instance of the object (i.e., something that you can put in a variable of type Classname), and they need to be called with variablename.InstanceMethodName(args). Static methods, on the other hand, refer to something that is always the same across all the times you use a class, and are often called "utility methods". These are referred to by Classname.StaticMethodName(args). (Also, static classes can contain static methods, but not instance methods. This is because they can never be instantiated, so there's never any instance for instance methods to be able to operate on.)
There are some times when you don't want to use a constructor for an instantiable class. One of these times is when the processing needed to create the class can throw an exception. (It's generally considered bad form for a constructor to get into a state where it could throw.)
Looking at your example, new LayoutInflator(getContext()) could potentially throw if it's passed something that it didn't expect, or if the Context it received didn't have the correct values that it expected. So, there's a static utility method that performs the new LayoutInflator() call, and then hooks up the things that need to be hooked up and sets the values that need to be set in the new LayoutInflator instance it just constructed so that it operates properly in the context you created it in. But, because it can only do that by getting information from the Context that it's passed, it could potentially throw if it tries to access a Context member that's null at the time it accesses it.
Most books I've seen have glossed over these concepts, and I know that my explanation might be confusing for you. That's why there's a chance for multiple people to answer.
And, here's some information to help you with this site in the future. What you're looking for is a book or course on Android programming. A quick search finds https://www.onlineprogrammingbooks.com/android/ as a potential resource, but I have not vetted the quality of these books; you could potentially also find Android programming courses either online or at a local community college. Also, you're not really asking about "doing something in Android Studio", you're asking about "doing something in the language used to program Android devices, which you program with Android Studio". And finally, the last question you asked ("what is the best way to learn Android programming using Android Studio?") would generally have the entire question closed as being too basic and broad for the site ('best' is subjective, and what works for one person doesn't necessarily work for another). But, I know how confusing everything can seem, and I want you to have a good experience here. I hope that this answer helps in some small way.
Creational design patterns. LayoutInflater.from(Context) is a static method, in that static method is an invocation of a constructor. Something has to call the constructor to create an instance. But that something could be internal to the class. See also Singleton pattern.
Like #Elliott explained. it uses a Singletone Design pattern. which means that the class doesn't have any public constructors, which explains why you can't create an object from it using the new keyword.
take a look at the documentation here . notice that it has 2 protected constructors.

Is it better to use local or global variables

Is it better to use local or global variables?
Let's say talking about 2000+ lines of android(java) service class, and all service is working on 'request' object and similar shared objects.
If I make everything local(keep inside of function), I need to pass many variables every time, or override same function many times. I need to make sure that objects, and sub objects are not null too.
If I make some variables global(across the class) I can share them, use them across the functions. Which I think will make everything easier.
What are the good sides and bad sides of defining variables inside of function or defining globally. In practice, and in theory(readability etc).
Is there suggested way?
Thank you.
Always prefer local over global. If you need to pass the data in as multiple parameters, so be it. At least then you're explicitly saying what data your function depends on. Having too many parameters is certainly a problem, but offloading some of them as globals isn't the answer.
If you rely on globals, it may not be as clear where certain data is coming from. If the globals are mutable, you'll have a mess on your hands as soon as you start to try to debug a difficult problem since it may not be obvious when certain global variables are being modified.
Note though that immutable constant globals aren't bad. If you have a constant that's needed in many functions (like PI for example), it makes sense to make it global. Immutable constants don't suffer from the drawbacks mentioned above since they can't change.
You wrote a 2000+ lines of service class. You completed the project. Cool ! Now after a month, you got a bug reported and are required to fix it.
Lets go through 2 different cases :
CASE 1
You are back on the service code. You see that the func1() uses globalVariabl1. Okay, but whats its value by now ? How does it change ? Who mutates the globalVariabl1 before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out.
CASE 2
You are back to you code, and see that the func0() fetches something and then passes it to func1(param1) as a parameter. You clearly know what the data is, how does it gets here.
In what case will it be easier to resolve the bug ?
Most of the time, CASE 2 will make it lot easier.
Local variables
Local variables would always help you. Even when you write the code and using local variables, the call statement will itself tell you that this function depends on this particular data. It helps you to be careful about what you are passing around.
Global variables
Global variables are okay when they represent the state of the class/object, or even when they are Constant (which should in general be all UPPERCASE letters). They can also be good when you just need to access the value frequently, and you know that the variable will always be initialised when you use it (for example initialising it inside onCreate())
There are no global variables in Java. You are referring to member variables. The basic rule is that variables should have the smallest possible enclosing scope.
I know the question is already answered and I upvoted Carcigenicate's answer.
To elaborate on his point I would suggest you try Test Driven Development practices. As soon as you start writing your code in conjunction with Unit test you will realize how bad Global variables can be and you will realize that you are writing code that cannot be tested without having to implement unnecessary Dependency Injection.
One more thing. Global variables are a huge mistake any time you start dealing with multiple threads and concurrency. It doesn't sound like you are dealing with that but keep it in mind any time you decide to make a Global variable.
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls.
If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.

Is using Java Reflection Bad Practice?

I am building an application for a client and I am in the situation where I need to have the ability to reference a field value via a string, i.e the users uses a string to define which field they want to change the value of, this is part of an abstract framework so technically I don't know the name of the fields they desire to change. Of course I could do this using hash maps, but I am considering using java reflection as this allows the fields to stay as fields of the object rather than the values being coded into a hash map. I have used reflection for my own personal work, but I was wondering if using Java reflection is actually bad practice, and I should stick to the hashmap methodology.
(Any other suggestions for solving the design problem described are also appreciated)
Thanks
The question itself is opinion based, although I believe most will agree that you can't just say "reflection is bad". Sometimes it's the only way, which is why a lot of libraries use reflection. Sometimes it's not the only way, but a workaround would be even worse. Sometimes it's not the only way, and not the easiest way, but the developer is far too amazed at the power of reflection to think straight.
Except for that last one there are plenty of valid reasons to consider reflection as a solution.
Personally reflection makes me sad, and in my experience there is almost always a better way. In the problem you described, setting variables based on a string i'd consider going with your hashmap idea which would reference variables via a string key which seems like exactly what you are describing. If you need the ability to reference values that do not exist you could also include factory methods to create variables when no key exists and then add to the map, if you are wrapping the objects then they will be passed by reference to avoid the problem you describe but this depends on the implementation (eg using Integer class etc for auto boxing if you are referencing primitives) Together this would allow for a much tighter and well defined implementation rather than reflecting values here there and everywhere. Apologies for the anti-reflection bias! Hope this helps.

which cannot be treated as the friend in contrast with oops

i need your help in understanding a question.
which of these cannot be treated as the friend in contrast with oop:
Function
Class
Object
Operator function
i think answer should be Operator function but i am not sure.please
anyone explain this to me.
thanks in advance.
Object.
An object is instantiated, the others are not.
Think about what 'friend' means. It's like schema, you're defining access, but it's all done at compile time... an object is a run time thing so friendship is meaningless and uninforcable. Once your code is compiled it's all reduced to pointers and references and no checks are done.
Also, to further clarify, to create friendship relationships between objects and other objects, or between objects and anything else, you couldn't do that at compile/code time, as you don't know what objects will exist and you can't reference them... Such behaviour, or similar behaviour anyway, COULD be implemented by a language, but the friendships would have to be added at run time, and this would be quite an interesting feature of a high level language, but quite a different feature to friendship as we know it.
Your question makes only sense for C++.
friend is not a contrast to OOP. friend helps OOP by allowing you to expose fewer member variables and member functions. friend allows you to expose your private members to one particular external component. Without friend, you would have to make the members public and expose them to the whole world.
Objects cannot be made friends. friend is a mechanism to control member access and hence, like public, protected and private specifiers, a compile-time issue. Objects, in contrast, exist a run-time[*].
An "operator function" (the correct word would be "overloaded operator") is not that much different from a normal function, really. You can mostly consider overloaded operators as functions with funny names. As far as friend is concerned, there is no difference whether you call your function Add or +, for example.
[*] I realise that this is a slight oversimplification when you consider template metapropgramming or constexpr.

What are some common Java pitfalls/gotchas for C++ programmer?

As the question says, what are some common/major issues that C++ programmers face when switching to Java? I am looking for some broad topic names or examples and day to day adjustments that engineers had to make. I can then go and do an in-depth reading on this.
I am specifically interested in opinions of engineers who have worked in C++ for years and had to work with Java but any pointers from others or even book recommendations are more than welcome.
In C++ you'd use destructors to clean up file descriptors, database connections and the like. The naive equivalent is to use finalizers. Don't. Ever.
Instead use this pattern:
OutputStream os;
try {
os = ...
// do stuff
} finally {
try { os.close(); } catch (Exception e) { }
}
You'll end up doing stuff like that a lot.
If you specify no access modifer, in Java the members are package-private by default, unlike C++ in which they are private. Package-private is an annoying access level meaning it's private but anything in the same package can access it too (which is an idiotic default access level imho);
There is no stack/heap separation. Everything is created on the heap (well, that's not strictly true but we'll pretend it is);
There is no pass-by-reference;
The equivalent to function pointers is anonymous interfaces.
My biggest hurdle crossing from C++ to Java was ditching procedural code. I was very used to tying all my objects together within procedures. Without procedural code in java, I made circular references everywhere. I had to learn how to call objects from objects without them being dependents of each other. It was the Biggest hurdle but the easiest to overcome.
Number 2 personal issue is documentation. JavaDoc is useful but to many java projects are under the misconception that all that is needed is the JavaDoc. I saw much better documentation in C++ projects. This may just be a personal preference for documentation outside of the code.
Number 3. There are in fact pointers in java, just no pointer arithmetic. In java they are called references. Don't think that you can ignore where things are pointing at, it will come back with a big bite.
== and .equals are not equal.
== will look at the pointer(reference) while .equals will look at the value that the reference is pointing at.
Generics (instead of templates), specifically the way they were implemented using type erasure.
Since you mention book recommendations, definitely read Effective Java, 2nd ed.—it addresses most of the pitfalls I've seen listed in the answers.
Creating a reference by accident when one was thinking of a copy constructor:
myClass me = new myClass();
myClass somebodyElse = me; /* A reference, not a value copied into an independent instance! */
somebodyElse.setPhoneNumber(5551234);
/* Hey... how come my phone doesn't work anymore?!?!? */
No multiple inheritance, and every class implicitly derives from java.lang.Object (which has a number of important methods you definitely have to know and understand)
You can have a sort of multiple inheritance by implementing interfaces
No operator overloading except for '+' (for Strings), and definitely none you can do yourself
No unsigned numerical types, except char, which shouldn't really be used as a numerical type. If you have to deal with unsigned types, you have to do a lot of casting and masking.
Strings are not null-terminated, instead they are based on char arrays and as such are immutable. As a consequence of this, building a long String by appending with += in a loop is O(n^2), so don't do it; use a StringBuilder instead.
Getting used to having a garbage collector. Not being able to rely on a destructor to clean up resources that the GC does not handle.
Everything is passed by value, because references are passed instead of objects.
No copy constructor, unless you have a need to clone. No assignment operator.
All methods are virtual by default, which is the opposite of C++.
Explicit language support for interfaces - pure virtual classes in C++.
It's all the little bitty syntax differences that got me. Lack of destructors.
On the other hand, being able to write a main for each class (immensely handy or testing) is real nice; after you get used to it, the structure and tricks available with jar files are real nice; the fact that the semantics are completely defined (eg, int is the same everywhere) is real nice.
My worst problem was keeping in mind the ownership of memory at all times. In C++, it's a necessary thing to do, and it creates some patterns in developer's mind that are hard to overcome. In Java, I can forget about it (to a very high degree, anyway), and this enables some algorithms and approaches that would be exceedingly awkward in C++.
There are no objects in Java, there are only references to objects. E.g :
MyClass myClass; // no object is created unlike C++.
But :
MyClass myClass = new MyClass(); // Now it is a valid java object reference.
The best book of Java "gotchas" that I've read is Java Puzzlers: Traps, Pitfalls, and Corner Cases. It's not specifically aimed at C++ developers, but it is full of examples of things you want to look out for.
Specifying a method parameter as final doesn't mean what you at first think it means
private void doSomething(final MyObject myObj){
...
myObj.setSomething("this will change the obj in the calling method too");
...
}
because java is pass by value it is doing what you're asking, just not immediately obvious unless you understand how java passes the value of the reference rather than the object.
Another notable one is the keyword final and const. Java defines the const as a reserved keyword but doesn't specify much of its usage. Also
object1=object2
doesn't copy the objects it changes the reference
All methods are virtual.
Parameterized types (generics) don't actually create code parameter-specific code (ie, List<String> uses the same bytecode as List<Object>; the compiler is the only thing that complains if you try to put an Integer in the former).
Varargs is easy.

Categories