Methods Checked Based On Reference Not The Object?

Jun 15, 2014

Check out the following basic code (assume that dog has a method called bark):

Dog d = new Dog();
Object o = d;
 
o.bark(); // error

But why? Isn't o just a pointer to a memory address which has the dog object? If so, why can't the compiler see that the object has a method called bark? Or, to ask the question another way, why is Java designed to check the object reference to see if the method exists instead of the object itself?

View Replies


ADVERTISEMENT

Inheritance Relationship Between Type Of Actual Object And Object Reference?

Apr 15, 2014

For example I create an object like this:

BankAccount b = new SavingsAccount();

Now lets say that I want to access a method 'addInterest()' that is in the 'SavingsAccount' class I would have to do: '((SavingsAccount)s).addInterest();'

The question I have is why do I have to cast 'b' to SavingsAccount? Isn't the actual object reference of 'b' already an instance of 'SavingsAccount' class? How does the 'BankAccount' affect the object itself? I'm really confused as to what class is truly getting instantiated and how BankAccount and SavingsAccount are both functioning to make the object 'b'.

View Replies View Related

Object Reference Variable Unwilling To Be Reset To A Different Object Type

Nov 6, 2014

I don't understand why the object reference variable 'a' cannot be recast from a thisA object reference to a thisB object reference.Is it the case that once a reference variable is linked to a particular object type then it cannot switch object types later on.I am facing the Java Associate Developer exam soon and I am just clearing up some issues in my head around object reference variable assignment,

class thisA {}
class thisB extends thisA { String testString = "test";}
public class CastQuestion2 {
public static void main(String[] args) {
thisA a = new thisA();
thisB b = new thisB();

[code]....

View Replies View Related

Equals Method - Take Object Reference And Return True If Given Object Equals This Object

Mar 28, 2014

Create an equals method that takes an object reference and returns true if the given object equals this object.

Hint: You'll need 'instanceof' and cast to a (Geocache)

So far I have:

public boolean equals(Object O){
if(O instanceof Geocache){
Geocache j=(Geocache) O;
if (this.equals(j)) //I know this is wrong... but I can't figure it out
return true;
}

else return false;
}

I think I have it correct up to the casting but I don't understand what I'm suppose to do with the this.equals(). Also I'm getting an error that I'm not returning a boolean... I get this all the time in other problems. I don't get why since I have to instances of returning booleans in this. "returns true if the given object equals this object" makes no sense to me. I assume the given object, in my case, is 'O'. What is 'this' object referring to?

View Replies View Related

Difference Between Object Reference And Object?

Dec 1, 2014

difference between object reference and object

View Replies View Related

How To Reference The Object

Jan 27, 2014

I am doing a Junit test case, but I keep having issues with AssertEquals ( object expected, object actual). I don't know how to reference the other actual object so that it can compare to the expected.

public void add (Distance d) throws CustomException

//I can also convert feet to inches and add all inches together and then divided inches to feet and inches
Distance result = new Distance();
int newFeet = this.feet + d.getFeet();
int newInches = this.inches + d.getInches();
if(newInches > 11)
{
newFeet = newFeet + (newInches/12);

[Code]...

View Replies View Related

How To Reference Object Created In One Class From Another

Oct 30, 2014

I have started working on a little project in my free time. It is just a simple text rpg that runs in a counsel window. I have 5 files each file contains 1 class.

public class SomnusCharacter {
private String gender = "";
private int age = 0;
private String race = "";
private int level = 0;
private int xp = 0;

[Code] ....

The chain of events right now is:

1. MainMenu is run
2. If user inputs n CreateCharactor is run
3. User inputs name, age, ect in SomnusCharacter object made in CreateCharacter
4. Intro (just rough demo for testing purposes) is run
5. If user inputs m Menu is run
6. Menu calls and prints out all the information from the object made in CreateCharacter

Step 6 is where I am having my problems. How can I reference (lets say the SomnusCharacter object made is called player) player from my Menu class? I know that if I made a new character that it would just create another SomunsCharacter object with the default values again.

View Replies View Related

Class That Needs To Be Copied Also Contains Reference To Other Object

May 22, 2014

I read somewhere : "Java use clone() method of Object class to copy content of one object to the other. The problem will arrive if the Class that needs to be copied also contains reference to the other object."Not able to understand the second line.

View Replies View Related

Cannot Assign Generic Object Reference To Similar Type

Jul 26, 2014

I have the following code:

public class CollisionManager<T> {
private boolean collision = false;
private T mainEntity;
public <T extends Entities> void handleCollision(T mainEntity, T secondEntity){
this.mainEntity = mainEntity; // This is illegal.
}
}

Why "this.mainEntity = mainEntity" is incorrect and also show me the correct way to achieve this?

The error I am getting is "Type mismatch: cannot convert T to T"

View Replies View Related

Create Instance Of Array Of Several Integers And Prints Data Based On Methods

Apr 15, 2014

I have to make two classes. The first one crates an instance of an array of several integers and prints data (average, greatest, lowest, et cetera) based on the second class, which contains the methods. I'm having a problem with the syntax for the first class required to use the methods.

Here's a shortened version of what I have right now just based on processing the number of integers in the array (because if I can get just one method properly connected, I could figure out everything else).

Driver

import java.util.Arrays;
public class ArrayMethodsDriver
{
//Creates the ArrayMethods object
public static void main(String[] args)
{
int[] a = {7,8,8,3,4,9,8,7};

[Code] ....

When I try to compile this, I currently get the "class expected" error on the count part.

View Replies View Related

Basis For Making Exception As Checked Or Unchecked

Oct 10, 2014

I know checked exception need to be checked at compile time and runtime exception need not be checked at compile time.

My question is not related to the definition.

The question is on what basis have they selected that FileNotFound exception is a checked exception and NullPointerException is an unchecked exception? Is it the random wish of the creator or is there reason behind why something is selected as checked exception and something as unchecked?

View Replies View Related

Why Compiler Compels Only Checked Exception To Be Put In Try Catch Clause Not RuntimeException

Mar 11, 2014

what is the use of checked exception.I know unchecked exception or Runtime exception are thrown by jvm whenever programmer makes any mistake in logic and current thread is terminated.But checked Exception are checked at compile time so that compiler compels programmer to put risky methods in try catch clause. And this checked Exception are caused due to problem in IO operation or any such operation which the programmer can't control.Programmer can't do anything to avoid this checked exception but can catch this exception.

Now the question is Why compiler compels checked exception to be put in try catch clause but doesn't complain anything in case of Runtime Exception???

View Replies View Related

Methods In Object Class

Jan 16, 2014

We know that all classes in Java extend the Object class. But methods in Object class are declared as public.I think if they were declared as protected, then also there wont have been any issue. So, what is the reason behind making them as public?

View Replies View Related

Get And Set Methods For Instantiated Object?

Oct 17, 2014

I am being told to (assignment) create a new Bread Object in another class than the original. But after that it is asking for get and set methods. Get and set methods of what? It's parameters?

class Bread
{
private static String breadType; //private field to hold bread type
private static int numberOfCaloriesPerSlice; //private field to hold calories per slice

public static String getBreadType() //get method
{
return breadType;

[code]....

View Replies View Related

Accessing Object Methods Within Arraylist

Oct 14, 2014

Scanner in = new Scanner(System.in);
ArrayList<rand> selectedRand = new ArrayList<Rand>();
selectedRand.add(new Rand(in.nextLine()));

I have created the most minimal code for creating an array list. I was wondering what the basic syntax of accessing objects methods that are within an Array List. So if I was to trying and get a method such as [.returnValue,] how would this look within a Rand object that is declared in a Array List Since you cannot simply declare a new Rand object and say:

newRandObject.returnValue();

And you must go through the actual slotted portion of the array list. I have searched the web and my text book for an example however none are provided.

View Replies View Related

Object / Methods - Private Instance Variables

Jun 30, 2014

so, i was reading my java book and learning about objects and methods and it starts talking about Encapsulation and mentions that it's good practice to set instance variables as private and instead of accessing the instance variables directly, we should create a set method and get method to get and set the stuff we want to pass to the class containing the object...

for example, in this class, we're passing the integer 70 for object dog one and integer 8 for object dog two for the dog class... and these these 2 integers are sent to the setsize method so we're not accessing instance variable size directly.

i dont quite get it though....if we the programmer are the one deciding what size the integer is for the dog, and the setsize method takes the one.setSize(70) or (8) and puts them in setsize(int s) as s... but only to copy that integer stored in s back to private int size.... why do we even need to bother with making these two extra methods such as setSize, getSize?

in the book it says that... well what if the code gets into the wrong hand and someone writes something like one.setSize(0) then you would get a dog with size 0 which is essentially illogical. but then again, i'm the programmer, and i am the person who writes the code and passing the right integer.The reason for public and private... that part i understand... i can see why if a variable's data can get changed amidst the code during calculations and you dont want it to directly change the original variable and have it mess up the code, but this code from the book just a bad example of demonstrating the reason? since we manually pass the information ourselves and passing it to method setSize... and all setSize does is stores it in another integer, only to copy it right away to size (which is the original private variable we were tryign to protect?

Any simple code to demonstrate how the code might end up changing an instance variable and why we would want to protect it by using private?

class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;

[code]...

View Replies View Related

Why Interface Inherit All Non Final Methods From Object Class

Jan 8, 2014

why interfaces inherit prototype of all the non final methods of the object class in itself? Object class is parent class of all the class and Interface is not the class.

View Replies View Related

Sort ArrayList By Object Field WITHOUT Using CompareTo Methods?

Mar 9, 2014

I have a project where I must sort a collection of songs by a number of fields: year, rank, title and artist. in the project, we must use certain methods and we cannot add others without getting marked down. Here are the specific requirements:

Sorting

The -sortBy option will cause the output to be sorted by a particular field. If this option is specified, the output should be ordered according to the field named. If there are ties, the tied songs should appear in same order in which they were in the input file. If no -sortBy option is specified, the output should maintain the order of the input file.

public void sortYear()

Order the songs in this collection by year (ascending).public void sortRank()
Order the songs in this collection by rank (ascending).public void sortArtist()
Order the songs in this collection lexicographically by artist (ascending, case-insensitive).public void sortTitle()
Order the songs in this collection lexicographically by title (ascending, case-insensitive).

Here is the relevant code:

SongCollection Class
Java Code: import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;

[code]....

View Replies View Related

Accessing Arraylist Member Object Methods In Enhanced For Loop?

Feb 24, 2014

I've tried a couple ways to do it, and they don't work. I'm aiming for functionality like I got with the regular for loop, but from an enhanced for loop. Is this simply beyond the scope of an enhanced for loop, or am I just not getting the right syntax?

TestObject to1 = new TestObject("first", 11);
TestObject to2 = new TestObject("second", 12);
TestObject to3 = new TestObject("third", 13);
TestObject to4 = new TestObject("fourth", 14);
TestObject to5 = new TestObject();
List<TestObject> testList;
testList = new ArrayList<TestObject>();

[code]....

The TestObject class is simply an int and a String, with getters getInt and getString. It all works fine with the regular for loop.

edit: I should probably mention that I know what I have in the enhanced for loop now will only display the class name and the hash. I've tried adding the .getString and .getInt, and tried a few other ways to make it work. I just reverted to this because it compiles and runs

View Replies View Related

Modify Values In Fields In Serializable Object Using Objects Set Methods Java

Dec 10, 2014

This program is basically complete. It compiles and runs. It is a college course assignment that I pretty much completed but for the last part in which I'm suppose to change the values of all fields and display the modified values using a toString method. Modifying the values of the fields is where I am stuck. I don't think I need to create a new text data file to do this. The instructor only asked that all the values of fields be changed and this was the last part of the assignment so I don't think it involves creating additional ObjectOutputStream and ObjectInputStream objects. I'm getting a NullPointerException error on line 161.Here is the code. I'm also including the input data file.

//create program so that objects of class can be serialized, implements interface Serialiable
//create constructor with 4 parameters with accompanying get and set methods, Override toString method
//create text file with 5 records, create Scanner object,ObjectOutputStream, and ObjectInputStream
//create new ItemRecord object, change values of all fields in ItemRecord object using object's set methods
//modify ItemRecord object using toString method

[hightlight =Java]import java.io.Serializable;
public class ItemRecord implements Serializable

[Code] .....

This is the error message:

----jGRASP exec: java ItemRecordReport

Item Cost Quantity Description
Number
A100 $ 99.99 10 Canon PowerShot-135
A200 $149.99 50 Panasonic-Lumix T55
A300 $349.99 20 Nikon- D3200 DSRL
A400 $280.99 30 Sony- DSC-W800
A500 $ 97.99 20 Samsung- WB35F
Exception in thread "main" java.lang.NullPointerException
at ItemRecordReport.main(ItemRecordReport.java:161)

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

Here is the data file:
A100 99.99 10 Canon PowerShot-135
A200 149.99 50 Panasonic-Lumix T55
A300 349.99 20 Nikon- D3200 DSRL
A400 280.99 30 Sony- DSC-W800
A500 97.99 20 Samsung- WB35F

Here is the data file for the modified field values.
B100 98.00 10 ABC1010
B200 97.00 15 DEF1020
B300 96.00 10 GHI1030
B400 95.00 05 JKL1040
B500 94.00 01 MNO1050

View Replies View Related

Created Tree Lemur Object - Returning Null Consistently From Methods

May 24, 2015

The question pretty much says it all, but I tasked myself with creating a program about lemurs. There are multiple class files in this program. In the below code snippet, I have my TreeLemur.class which extends to the Lemur.class which extends to the Mammal.class. However, when I create a Tree Lemur object in the main program, it is returning null consistently from certain methods. What am I doing wrong here?

TreeLemur.class :

public class TreeLemur extends Lemur {
private String groupSize;
private String diet;
private String fur;
public void setGroupSize() {
groupSize = "
Group Size: Large";
}

[Code]...

As of yet, I'm just trying to get Tree Lemur working properly to continue with creating the other if-branches within the main program.

View Replies View Related

Passing Object Argument To A Method - Unable To Call Methods On Argument

Feb 7, 2015

I am trying to pass an object of type Product p to my editProduct method, however trying to call p.getName(); doesn't work and throws a NullPointerException. The same kind of thing works for my displayRecord method (in a different class) and I can call .getName() on Product p, also passed as an argument to that method. Below is my editProduct class. The NullPointerExcepion is being thrown at line 61 (i.e., nameField.setText(p.getName());).

I don't know if I explained right, so here's a line thing of how the classes relate:

Search >>>(field.getText())>>> displayRecord(Product p) >>>editProduct(p)>>> EditProduct

And as a side note: adding the line p = new Product(); fixes it and successfully runs the class (including the Save and Quit parts) but obviously I want it to specifically refer to the Product I pass to the method.

Java Code:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;

[Code] ....

I'm asking a question because I don't understand how Product p could possibly be null, because the argument is passed through my DisplayRecord class, which also takes a Product p argument and works. In that class, I have declared Product prod = p; and prod is what I am passing to editProduct.

View Replies View Related

Int Is Not A Reference Type

Jan 24, 2015

I don't really know what this means and it is sending an error when I try to run my program I am trying to set the x and y value (Int x and int y) to setVisible false at a specific time in my game but it keeps sending the error that int is not a reference type.

View Replies View Related

Cannot Pass By Reference?

Aug 25, 2014

I'm fairly new to Java, I'm very experienced with C++ and C# in which you can pass by reference - extremely useful. Take for example this bit of code in C#:

class MyClass
{
public MyClass(int i)
{
m_i = i;
}
  public int m_i;

[Code] ...

Just at the end of this program x.m_i will be equal to 8. As far as I can see this is not possible in Java: you can't pass a double by reference, using a Double will kick in the autoboxing so that won't work either. The only "solution" in Java would be to pass in a double[] (of length 1) or to make a wrapper class, both nasty solutions because a user may want to just hold a double as a member of their class just as I have, for reasons such as not allocating more memory for a class and generally not being bloated.

View Replies View Related

How To Reference Action Listeners

Mar 15, 2015

I am making an MVC program and I am not allowed to put the action listeners in the view class. I was able to get one button working fine but since I am unable to reference them I cannot give them both individual responses.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
HobbyList model;
ListView view;

[code]....

View Replies View Related

How To Reference Input Into Another Method

Apr 17, 2014

public class {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] numbers = new double[10];
System.out.println("Enter " + numbers.length + "numbers");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextDouble();

[Code] .....

I am trying to reference the input "numbers[i]" to my mean method, how do i do that?

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved