How To Call Classes Within Other Classes
Apr 18, 2014How do you call classes within other classes? Or can you only call classes through the main?
View RepliesHow do you call classes within other classes? Or can you only call classes through the main?
View RepliesHow do i call the method without using inner classes in this example:
jt = new JTable (model) {
public boolean isCellEditable (int row, int col) {
if (col == 5) {
return false;
[Code] ....
how come you can call non static methods from other classes(objects when they are created from main) but not static methods in the same class as the main method??
example I cannot call the method maximum from the main method aslong as its not static BUT i can call other objects non static methods from main??
class test{
public static void main(String [] args){
Scanner input = new Scanner(System.in); //create new Scanner object
//for input
int number1;
int number2;
[Code]...
The requirements are as follows:Design and implement the class Day that implements the day of the week in a program. The class Day should store the day, such as Sun for Sunday. The program should be able to perform the following operations on an object of type Day:
A. Set the day.
B. Print the day.
C. Return the day.
D. Return the next day.
E. Return the previous day.
F. Calculate and return the day by adding certain days to the current day. For example, if the current day is Monday and we add four days, the day to be returned is Friday. Similarly, if today is Tuesday and we add 13 days, the day to be returned is Monday.
G. Add the appropriate constructors.
H. Write the definitions of the methods to implement the operations for the class Day, as defined in A through G.
I. Write a program to test various operations on the class Day.Should I break down my day.java into several separate classes, one for each of the sections (previous, next, etc)?
import java.util.*;
public class MyDay
{
static Scanner readinput = new Scanner(System.in);
String day;
public MyDay(String day)
{
day = "Sunday";
[code]....
Ideally I would like to create a Gui that would have someone type in the day, and then press a button to return the next day, prior day, or have a text input to test for adding X number of days.
I'm doing an aggregation exercise that's suppose to find the volume and surface area of a cylinder. What I'm trying to do is pass values from one class, to a second class, and that second class passes values to a third class.
This may be a clearer explanation: The first class is the main program which sends values to the second and third class. The second class is used do calculations for a circle (a pre-existing class from another assignment). The third class grabs the values that the second class calculated and calculates those values with the one that was passed from the first class to the third class. The first class then prints the outcome.
Problem is when the program gets to the third class, it just calculates the value from the first class with the default constructor from the second class. It's like the second class never received the values from the first class. I think I'm missing a step, but I don't what it is.
First Class:
package circle;
import java.util.Scanner;
public class CylinderInput
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
//user defined variable
[Code]...
Why do we get such output or which line of code produces the output?
1class Egg2 {
2 protected class Yolk {
3 public Yolk() { print("Egg2.Yolk()"); }
4 public void f() { print("Egg2.Yolk.f()");}
5 }
6 private Yolk y = new Yolk();
[Code] ....
/* Output:
1.)Egg2.Yolk()
2.)New Egg2()
3.)Egg2.Yolk()
4.)BigEgg2.Yolk()
5.)BigEgg2.Yolk.f()
*///:~
I'm quite new to Java. I have some trouble with understanding how to get two classes to get objects from each other (if that is the correct term).
Lets say I have a login class, in which I have a method checking what the user has entered into the console (I have not displayed the whole code, but this class works as it should and give the user an option to enter username and password and return it true if entered correct).
public static boolean validateUserPass(String userName, String password) {
String[] user = {"admin"};
String[] passwords = {"firkanten"};
boolean check = false;
for (int i = 0; i < user.length; i++) {
if (userName.equals(user[i])) {
if (password.equals(passwords[i])) {
check = true;
Now, in another class I want a display box to appear on the screen and give the user three options: Click yes, no or cancel. I get this to run perfectly alone, this is not the hard part for me. I want the display box only to appear when the correct username and password is given, but I can't seem to figure out how to do this probably.
Regarding the code examples in Head First Java, this is from Chapter 5, regarding the beginning creation of the dot com game. There are two classes in quesiton
the first is the SimpleDotComTester class:
public class SimpleDotComTester {
public static void main(String[] args)
{
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2, 3, 4};
dot.setLocationCells(locations);
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
}
and the second one is the code for the checkYourself () method in the SimpleDotCom class
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs)
[code]....
Now I noticed that both classes use a variable called result; the program runs fine, but assume from the example that you can use the same variable name two different classes;
design a class to conduct a survey of three hospitals. you want to know how many sectors (eg operation, children, gastronomic) each hospitals have, and how many doctors there are in each sector.
what is the process of class design?
I have a Date class and Time class. Is it possible to pass Time object inside Date constructor so that toString function gives output as 12/05/2013 06:31:30 ?
View Replies View RelatedI have two classes.
First and Second.
In First class I want to use methods from Second class. So:
Java Code:
Second s = new Second();
s.secondMethod(); mh_sh_highlight_all('java');
Second thing I want to do is use JTextArea from First class in Second class.
So since it gives me error, I extended First class with Second:
Java Code: public class Second extends First { mh_sh_highlight_all('java');
It look like it should work, no errors etc. Also both things are working separately. But since I used both at once...
Java Code:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at package.Second.<init>(Second.java:7)
at package.First.<init>(First.java:17) mh_sh_highlight_all('java');
I can move what I need to First class, and it will work fine, but I want to make this in two classes. But I really don't understand extends, I just use them if there is need for them. So I don't know how to handle this problem.
I also tried to extends Second just like First:
Java Code: public class Second extends JPanel implements ActionListener { mh_sh_highlight_all('java');
Instead of extending First, but it can not be done, since ActionListener is in First...
Well. Also addActionListener can maybe solve my problem?
I'm using:
Java Code: xx.addActionListener(this); mh_sh_highlight_all('java');
Maybe I can use something instead of this? But what?
Wondering, what is exactly reason for existence of inner classes? Are there problems that without them you can not resolve?
Anything beside emulate multiple inheritance - when your class need to extends the real classes, and not implement multiple interfaces ?
I have a folder of classes that I am packaging together. Some classes are being packaged and compiling just fine. My other classes in the same package, however, are saying that they cannot find these classes.
View Replies View RelatedWhat i'm trying to do is to pass a bufferedreader string from main method to a class that will set on how fast or slow a message will be displayed but it has to be displayed on a JTextArea that's in a constructor class.
import java.awt.*;
import javax.swing.*;
public class demo {
JFrame frame = new JFrame ("Idle Game Test!");
JPanel backGroundPanel = new JPanel ();
JPanel statusPanel = new JPanel ();
JPanel buttonPanel = new JPanel ();
JPanel bigPanel = new JPanel ();
JTextArea message = new JTextArea ();
[code].....
So I prefer to use Emacs rather than using Eclipse or some other IDE and I am wondering how to include external classes in my main file?
For instance I have my main file (the one that includes my 'main()' function) and then I have another class (seperate file(s)) for creating a GUI, or making a game and using a Player class, Weapon class, etc. How can this be done? Do I just use 'extends myclass'?
I would like to use the attribute A of my class Selecter1, in my main class Resizing. How?
View Replies View RelatedI have been using Guice for a while but just now run into a need to use anonymous inner classes. In the example below Car and its dependencies do not get injected resulted in NPE on consecutive calls. How can this be changed to work properly? Do I need to add extra binding?
public class Truck {
@Inject
public Truck(Engine engine) {
this.engine = engine;
}
public Car getCar() {
[code]....
Is it possible to combine two classes that I have defined to contain some of the same elements so that NetBeans stops giving me errors? I don't want to get rid of any necessary code, and if both classes are necessary, should I just rename one of them? One class is an ArrayList that I am using to write the information for employees entered to a text file "employee.txt." I also want users to be able to call on this information via employeeID in order to display employee information. The code is the following:
public ArrayList<Employee> getEmployees() {
// if the employees file has already been read, don't read it again
if (employees != null)
return employees;
employees = new ArrayList<>();
if (Files.exists(employeesPath)) // prevent the FileNotFoundException {
[code]....
The other class is a getEmployee class that I previously defined before attempting to read the information from the text file and display it in the console. It is as follows:
private void getEmployees() {
try {
// if the file doesn't exists, create it
if (!Files.exists(employeesPath))
Files.createFile(employeesPath);
BufferedReader in =
new BufferedReader(
new FileReader(employeesFile));
[code]....
What programs use abstract classes?
View Replies View RelatedI am new to Java and I am doing an assignment to identify Class and Attributes from below example. How to identify 7 classes and its attributes from this scenario:
ABC Maps Maker produces electronic maps for global positioning systems. Every map needs to define the latitude and longitude of the centre of the map, together with the length and breadth of the map. A map also has a name, and a set of geographical features.
A geographical feature is something noticeable in a a map; e.g., a hill, or valley. Among the types of features are the following: trace features, track features and tract features.
All features have a name that is displayed on the map next to the feature. A trace feature has a coordinate point to indicate its location relative to the centre of the map. Broadcasting stations, mountain peaks, and transmission towers, are examples of trace features. Every trace feature has a description associated with it.
Examples of track features include roads, railways and rivers. Each track feature has a list of points that define its course, and a line pattern. The line pattern specifies the colour, and the thickness.
Like a track feature, a tract feature also has set of points, except that when drawn on the map, the last point is linked to the first point to enclose a complete region. Additionally, it has a fill pattern which incorporates essentially a colour.
Recall that there is a class, Point, in the java.awt package – this can be used to hold the co-ordinate of a point
Class:
Attributes:
I just want to clarify generics for classes.
Referring to [URL] ....
Generics means all methods in class Box will return an Integer if their parameters are defined as T when the instantiation is :
Box<Integer> integerBox = new Box<Integer>();
Are those Boxes only can contain Integers? Can I write
Box <Toys> toybox = new Box <> ();
To show that the Box only contain toys?
I am working my way through "Head First Java" and typing the code in the book into Notepad++ as I go. In the first few chapters the code was simple and only had one class (main). Now the code has two or more classes. Originally I would compile the code in the Command Window by typing "javac" and the program's name. After it compiled I would execute the program by typing "java -classpath . " and the program's name. However, now when program has several classes I get the following error: Could not find or load main class. Below is a program I am having issues with... does it need to be saved as two separate files?
class DogTestDrive {
public static void main (String [] args) {
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
[Code] ....
Class 1:
view sourceprint?
1 public class one {
2 public static void main(String[] args){
3 int num = 0;
4 System.out.println(num);
5 two.change(num);
[Code] .....
This should print 0, then 1, but it prints 0, then 0. How do I make it print 0 then 1 with the same format?
I have to make a retail item class that has description, price and quantity. I then have to make a CashRegister class that calculates subtotal, tax, total and displays it (toString). I also have to make a driver class to call the methods from main. I have no clue what I am doing and what I have done does not work. I am trying to make it sort of like a cart, in the CashRegister it should ask the user to enter the description, quantity purchased and the price. Then it would send that to the arraylist of retailitem. I am having trouble using those items in my other methods and then do not know how to call those in the driver class.. So here are my classes:
public class RetailItem {
private String description;
private int quantity;
private double price;
public RetailItem(){
description = "";
quantity = 0;
[Code] ....
I'm working on a University project creating a simple game using Netbeans but I'm totally stuck. I've created a number of classes to perform various methods, such as throwing back formatted text but I can't get them to work from within a Swing GUI created in Netbeans.
The Main method simply creates an instance of another class called Game which then itself creates instances of a number of other classes (textEngine, timer) and also a Swing GUI Class. The GUI appears on screen ok and I've been able to get methods working inside the GUI such as changing pictures and text when clicking a button. But I CANT get the GUI class to recognise the instances of the other classes or access their methods. I've created an instance of the TextEngine class called tEng. So I type this code in the GUI class:
textField.setText(tEng.getPhrase(2));
getPhrase() returns a String based on the number passed in the argument. But Netbeans reports an error that tEng is not recognised as a symbol despit it being a member of the same package. Creating the instance of the class within the GUI class likewise fails:
TextEngine tEng = new TextEngine();
Again the class is not recognised.
i have tried moving the
//create line
Point beginOfLine = new Point(point1, point2);
//ask user for second pair of coordinates
System.out.print("Enter the coordinates for X2 or <Random> or <Exit>:");
userInput=keyboard.nextLine();
code part to another class but nothing..this is what a second class should be doing
1 - Write a java class called Point to represent a 2-D point (With x and y)
- The constructor should take the x & y as double
- The class should have accessor / mutator methods for all coordinates
2 - Write a java class called Line to represent a line (with a starting point and an ending point)
- The constructor arguments are the start and end points
//import utilities to be used in the program
import java.util.Scanner;
import java.util.Random;
public class Point {
//declare variables
private double pointX, difX;
private double pointY, difY;
[code]....