Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
I have 3 classes handling data members:
Save
Memory
Number
 
each with a Ctor, setters, getters, and various other things they require.
And data members.
 
I have a class:
Calculator
 
which has to operate on the variables stored in the aforementioned classes.
 
I don't want to create objects from those classes in Calculator, since I already created such objects from main()!!!!
 
So how can I access them?
 
I tried changing the functions to static,
for instance:
 
public static double Add() {
return Number.getNumber() + Save.getSave();
}
 
(in Calculator, which is an abstract class...)
 
That would be how I'd access static methods in abstract classes, but but it wouldn't let me, since they handle data members - I couldn't even change the methods to static without getting an error...
 
If I were to create a new object from, say, class Number, it would have its own data members, whereas I want to access the data members in the object created by main()!!!
 
Can I retrieve a reference and use it somehow, or something like that?
 

Thanks for helping.
Posted 28-Dec-12 4:05am
Edited 28-Dec-12 4:28am
v4
Comments
TorstenH. at 30-Dec-12 2:58am
   
You really need to read about OOP and the usage of variables.
This looks really odd, that's not the way to use any programming language.
 
PLease follow the link I posted about the abstract classes,there is a complete Java Tutorial behind it, really well written.
 
Also, please get a decent JAVA book that you can place beside your keyboard to have a look at topics while coding. Books are still a perfect source for learning.
 
EDIT: I have added another solution, please check it out. it explains the basic rules of abstraction
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Please do not use static. You should create instances or use the given instances in Calculator by using setters there:
 
public class MyCalculator extends Calculator{ // extending the abstract class

  public MyCalculator(){
    this.ignition();
  }
 
  private void ignition(){
    // this is where the fun starts

    setIntegerValue(2); // example for an inherited setter from Calculator
  }
 

 
  public static void main(String[] args]{
    MyCalculator oCalc = new MyCalculator(); // break out of static context
  }
}
 
  Permalink  
Comments
teledoar at 28-Dec-12 11:32am
   
Err... calculator doesn't have any data members, so it doesn't have a setter.
I'm trying to use the getter function from classes Save and Number in class Calculator.
TorstenH. at 28-Dec-12 14:01pm
   
whatever. it's an example.
I do not have your classes and therefor do not know what's inside.
 
You can see in that example how to extend a given abstract class and how to use it's methods in a non-static way.
Please try to develop from that scratch your own code.
teledoar at 28-Dec-12 15:53pm
   
Point is, my classes don't inherit from Calculator, they are entirely unrelated to it or each other, they are there simply to hold data and code, but they need to use variables and functions from one another. That is the problem, I already know how to inherit things.
 
By now, I solved it already by making everything - variables included - static. Now I can access them all from everywhere;
 
I'd still like to know how to access methods (and/or) variables in unrelated classes that are not abstract/static. (public ones, naturally). 'Cause so far I've been stymied whenever I tried.
TorstenH. at 29-Dec-12 5:13am
   
Your design is leaking just a little bit (like e.g. a waterfall).
 
You should read about the concept of abstract classes ( Abstract classes @ the Java Tutorial ).
You need to extend the abstract classes - you can also do so beside of your existing code and then use the extending classes (YES, by variable and instance, cause that's how programming works!)
 
Using static just to be able to access variables is bad, really bad.
teledoar at 2-Jan-13 13:47pm
   
I asked my teacher and he explained to me what you've meant by "leaking". Anyway, he says what I did in the first place ought to have worked, and didn't know why I got red all over it without me showing it to him.
 
Unfortunately, I already turned it all to static, and change the reference to all of it all over my classes to a static way, so now I have to change it all back before I can try and see why it didn't work.
 
If only I had the time...
 
Thanks, anyway.
teledoar at 2-Jan-13 13:50pm
   
I think I should have written:
public static double Add() {
return Calculator.Number.getNumber() + Calculator.Save.getSave();
}
TorstenH. at 2-Jan-13 15:44pm
   
check out Solution 3, that is what you need.
 
Yes, it might have worked and if you have a chance to change access to the methods in the abstract class to static, you can also do that too.
Normally you can not alter a method of a abstract class in an extension to be static - that is not allowed.
Often one has to deal with libraries, where a class is given and needs to be extended. One can not change the given classes / objects, but has to cover own functionality.
 
As an example: I do so often with GUI components. I add some functionally to them by extending them.
Like highlighting when mandatory fields that are empty or validation routines on text fields that the user enters e.g. telephone number or zip code.
Also are tables always custom - one just uses a base class / an interface that get's extended / filled to what is needed.
 
Please count it as a lesson learned and remember next time.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

public class ExampleClass
{
    public string ECName { get; set; }
    public int ECIndex { get; set; }
    public string ECDescription { get; set; }
 
    public bool checkOtherClassValue(OtherExampleClass oecTemp)
    {
        if (oecTemp.someValue == "someValue")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
 
public class OtherExampleClass
{
    public string someValue { get; set; }
    public int oecIndex { get; set; }
}
 

Then, in main, create both of your objects:
 
    //Create an object of one class
    OtherExampleClass oecTemp = new OtherExampleClass();
    //set some values...
    oecTemp.someValue = "someValue";
    
    //create an object of another class
    ExampleClass ec = new ExampleClass();
    //pass the first object as a param for the method in the second class

    bool result = ec.checkOtherClassValue(oecTemp);
 
You could also create a getter method in main that returns the object based upon a requested index or name etc.
  Permalink  
Comments
TorstenH. at 30-Dec-12 2:54am
   
not what he needs - OtherExampleClass is not abstract.
He want's access to an abstract class without regarding the basic design rules.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

OK, let's try again.
 
I created a class Application.
This is my application - surprising, I know.
Please also regard the break out of the static context.
 
There is an abstract class MyAbstractClass that has some method.
And there is a class MyClass that extends MyAbstractClass.
 
There is also a function parseIntFromString(int), that is part of the abstract class. I'm changing it in MyClass, so it returns the result I want (That works as long as a function is not set "final").
 
With the help of this extension MyClass I can access all the functions of the abstract class MyAbstractClass, as you can see in the function ignition()
 

package com.cp;
 
public class Application {
	
	public Application(){
		this.ignition();
	}
 
	private void ignition() {
		MyClass oMyClass = new MyClass();
		
		// using method from MyClass
		System.out.println("The result is " + oMyClass.tellIfPositive(3) );
		
		// using method from abstract class via MyClass
		System.out.println("The result is " + oMyClass.tellIfTrue(0));
		
		// using altered method - abstract would return 0
		System.out.println("The result is " + oMyClass.parseIntFromString("2"));
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Application(); // break out of static context
	}
	
//	#############################################################
//	Extending the abstract class
//	it inherits the functions of the abstract class and can have additional functions.
	public class MyClass extends MyAbstractClass{
		
		public MyClass(){ /* doAny(); */}
		
		public boolean tellIfPositive(int iValue){
			if(0 <= iValue){ return true; }
			return false;
		}
		
		// function is altered to return result we need
		@Override
		public int parseIntFromString(String strValue){
			return Integer.parseInt(strValue);
		}
	}
	
//	##############################################################	
	// abstract class with a method we want to use.
	public abstract class MyAbstractClass {
 
		// just a simple function, nothing serious
		public boolean tellIfTrue(int iValue){
			if(1 == iValue){ return true; }
			return false;
		}
		
		// function that is going to be altered in MyClass
		public int parseIntFromString(String strValue){
			return 0;
		}
	}
	
//	################################################################

}
 
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 350
1 Jochen Arndt 190
2 Richard MacCutchan 135
3 Sergey Alexandrovich Kryukov 120
4 DamithSL 105
0 OriginalGriff 6,045
1 DamithSL 4,611
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,310


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 30 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100