Getters returning null - java

I know why my problem is occurring but i'm unsure on how to deal with it.
So I have 3 classes, 1 of these holds my getters & setters. In one class I am setting the values, in the other I am getting the values. When I get the values they are returned null. This is obviously because the two instances of the getter/setter object I created in the classes are separate from one another. What i'm trying to find out is how I can set the values in one class and get them in another without having two separate instances of the getter/setter class. My wording is terrible so here's a more visual explanation:
Class 1
Encapsulation encap = new Encapsulation();
encap.setValue(10);
Class 2
Encapsulation encap = new Encapsulation();
encap.getValue(); //I want this to return 10
Class 3 (Encapsulation)
private int value;
public void setValue(int value){
this.value = value;
}
public int getValue(){
return value
}

In Class2, you are creating a new instance of class Encapsulation. (Notice new Encapsulation()). So obviously, that won't hold the values.
Instead, I would suggest you two solutions:
First:
Save that object in an Application class as you are working on Android application.
public class TestApplication extends Application {
public Encapsulation tempClass;
public TestApplication () {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
public Encapsulation getTempClass() {
return tempClass;
}
public void setTempClass(Encapsulation tempClass) {
this.tempClass = tempClass;
}
}
Now in your Activity:
//after setContentView
testAppObj = (TestApplication) getApplication();
testAppObj.setTempClass(myTempClassObj);
//retrieve as:
Encapsulation obj = testAppObj.getTempClass();
You must register your Application class in your manifest file just like you register your activities:
<application
android:name="com.pkg.test.TestApplication " />
Second:
Keep object encap as static in Class1. So you can access it from calss2. (I don't prefer static.)
Hope it helps.

Make value static, it will keep the same value across all Encapsulation instances
private static int value;
public void setValue(int aValue){
value = aValue;
}
public int getValue(){
return value;
}

Just declare an object of the Encapsulation class once,and use the same instance to call the getter and setter.
Like this:
Encapsulation encap = new Encapsulation();
encap.setValue(10);
encap.getValue();
It works.

Related

Instantiate public object inside method

I'm trying to instantiate an object inside a method of a class so it can be used anywhere in the class. I come from a python background and it is quite easy, you can just pass the instantiated object to an instance of it's "self" like below.
self.camera = CameraInstance()
How do you do this in Java? I tried something like below but it doesn't like it.
private void init_camera_settings() {
public CameraInterface camera;
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
Both methods are in the same class. The reason for this is because I only want to instantiate the camera object only in certain scenarios.
Thanks!
You can't declare a field inside a method. In Java, a type either has a field, or it doesn't. Every instance of the same class has the same set of fields.
But you can declare the field (not in a method) and decide to only assign a value to it in a method:
// Note: avoid public fields
public CameraInterface camera;
private void initCameraSettings() {
camera = new Camera();
}
private void someotherMethod() {
camera.takePhoto();
}
(The field will have a default value, in this case null, until you assign a different value to it.)
As an aside, I'd strongly advise against public fields. I make every field private, and add properties to allow access where necessary. This allows you to change implementation details later. The one exception to this is public static final fields of immutable types, basically for constants, but even there I'd be cautious.
To use the variable throughout the class in different methodsm the variables should have class scope. You usually use new to create a new Object
public MyClass {
public CameraInterface camera = new Camera ();
private void init_camera_settings() {
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
}
self.camera = CameraInstance()
is equivalent to:
class Foo {
private CameraInstance camera;
public Foo() {
this.camera = new CameraInstance();
}
// use "this.camera" in methods.
}

Using object reference to get methods from another class

So I have a concrete class and an abstract class and I am trying to access methods from the concrete class from the abstract one. Store currently contains many getters that the member class needs. Currently get null pointer exception.
public abstract class members{
// Trying to refrence the store object
Store store;
public void someMethod(){
// I want to be able to access all the methods from the store class
// eg
store.showVideoCollection();
}
}
public class store {
// This class has already been instantiated, just one object for it.
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
EDIT:
In the main method
public class start {
public start() {
store = new Store(); // Don't want to create more than 1 store object.
}
Thanks
In order to store a Store instance you must instantiate it. As is, you declare the variable store but you never initialize it (so it's null). I think you wanted something like
// Trying to refrence the store object
Store store = new Store(); // <-- create a Store and assign it to store.
Alternatively, you could make Store a Singleton. The linked Wikipedia page says (in part) the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
public final class Store {
public static Store getInstance() {
return _instance;
}
private static final Store _instance = new Store();
private Store() {
}
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}

Call methods of specific other object

I want to create an object that is linked in some way to another object of the same class. This link should be specified in the constructor of the new object.
public class Counter {
public Counter(){
// default counter constructor
}
public Counter(Counter oldCounter){
// do stuff specifying new object is linked to oldCounter
}
public void someMethod(){
// this method should call a method belonging to oldCounter
oldCounter.someOtherMethod();
}
Tried searching the archives for an answer, but couldn't find anything...
Remember the argument as a private instance member, then use that member:
public class Counter {
// The instance member we'll use, note that we initialize it to `null`
// because you have a zero-args constructor, so we want to be sure we
// know whether we have one or not
private Counter otherCounter = null;
public Counter() {}
public Counter(Counter oldCounter) {
// Remember it here
this.otherCounter = oldCounter;
}
public void someMethod() {
// Use it here
if (this.otherCounter != null) {
this.otherCOunter.someOtherMethod();
}
}
}
To achieve what you want Crowder's answer is good enough.
You are having two version of same class. For me it seems that you need to follow some design pattern to better organize your code. In this case Factory Pattern may be a good choice.

How to call a generic method using super class

I have got some methods that are common to two subclasses so i have put them in Abstract superclass but there is one method that uses a variable with two different values so i am confused how to implement that method the code is like:
StandardMember class got this method with its own different value for remainingCredit=30 at starting
public void borrowHolding(int holdingId)
throws InsufficientCreditException, MultipleBorrowingException {
// TODO Auto-generated method stub
System.out.println("Hello");
Holding tempHolding = Library.libCollection.getHolding(holdingId);
if (Library.libCollection.getHolding(holdingId) != null) {
if (tempHolding.isOnLoan()) {
System.out.println("Can not be issued Currently on Load");
} else {
System.out.println("Can be issued");
remainingCredit-=tempHolding.getDefaultLoanFee();
System.out.println(getRemainingCredit());
tempHolding.setLoanCheck(true);
currentlyBorrowedHolding.put(holdingId, tempHolding);
System.out.println(remainingCredit);
System.out.println(holdingId);
}
}
PremiumMember Class got same method but the value of remainingCredit is 45, Whereas all the methods common to them are implemented in this AbstractMember class which implements the Member interface. but when i try to call these method from other class i have to initialize the object of AbstractMember in Library Class like this
Member member = new StandardMember();
which is very bad because I can not use the StandardMember object to run the PremiumMember Object's version of same method. so, either i should create new object of PremiumMember Class or i dont know what to do. but if i create two objects then this member object is being used in borrowHolding method which is basically a cascading method in Library Class which in turn calls the borrowHolding method in Member Interface:
public void borrowHolding(int holdingId) throws InsufficientCreditException, MultipleBorrowingException {
if(libCollection.holdingMap==null){
System.out.println("Collection is Empty");
}
if(libCollection.holdingMap.containsKey(holdingId))
member.borrowHolding(holdingId);
}
the problem is i can not create two objects because at runtime i can only call one method. so help me out how to implement this method in Abstract class so that program will detect the difference that which object it should create.
If I understood you correctly, you have a Member abstract class with a field remainingCredit which has to be 30 in one subclass and 45 in another.
Use a protected constructor.
public abstract class Member {
private int remainingCredit;
// Other members
// getters and setters
protected Member(String memId, String memName, int remainingCredit) {
this.memId = memId;
this.memName = memName;
this.remainingCredit = remainingCredit;
}
}
public StandardMember extends Member {
public StandardMember(String memId, String memName) {
super(memId, memName, 30);
}
}
public PremiumMember extends Member {
public PremiumMember(String memId, String memName) {
super(memId, memName, 45);
}
}

Using the keyword "this" in java [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word

Categories

Resources