Two Laptop Bag
The moose likes Java in General and the fly likes Help with Code.. Help with Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Help with Code.. Help with Classes" Watch "Help with Code.. Help with Classes" New topic

Help with Code.. Help with Classes

Avin Sinanan
Ranch Hand

Joined: Nov 07, 2001
Posts: 109
Ok examine the code.. its now long..actually its very simple.. read it and i will tell you the problem i am having...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class StringClass
public static void main(String[] args)
int age ;
Class1 firstClass = new Class1();
age =firstClass.method1();
System.out.println("my grandfather is" + age + "old");
class Class1
int fatherAge ;
int grandFatherAge;
public Class1()
public int method1()
/*Lets assume that a textField appears at this point and the user
is allowed to type in fatherAge..lets assume in this case they typed
in 30. Now this means grandFatherAge is highly variabele and grandFatherAge
depends on fatherAge.*/

fatherAge = 30;
grandFatherAge = fatherAge + 25 ;
return grandFatherAge ;
class Class2
public Class2()
/* I would like to know how to print grandFatherAge in class2*/
System.out.println("My Grandfather died at" + grandFatherAge);

Now look at Class2... how am i suppose to print grandFatherAge?
The problem with granfatherAge is that i must print it in class2
and the values must be produced in Class1.
Now I cannot use the line of code in Class2
Class1 secondClass = new Class1();
int grand = secondClass.method1();
System.out.println("My Grandfather died at" + grand);
because i had to create another Class1 called secongClass and this class does not conatin the original value typed ib first (ie. 30)
How do i print at what age my grandfather died. Now i have to keep all three classes i cannot take away any classes because this is bacsically a simplication of a very complex project i am working on.
Is there some kind of getmethod that i can use.. and also remeber Class2 had to regognise the class "firstClass".

yours respectfully<br />Avin Sinanan
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Since grandfatherAge is an instance variable you'll need to have an instance of class1 in order to access it. The first question is what is the relation between class1 and class2? How do they work together or are they completely unrelated? The simplest way would be to have an instance variable in class2 that is a class1 object, then each instance of class2 would have an instance of class1 and could access all of its public variables through that instance.
hope that helps

I agree. Here's the link:
subject: Help with Code.. Help with Classes
jQuery in Action, 3rd edition