class A{
String z(){
System.out.println("a");
return "sauarbh";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner {
public static void main(String[] args) {
B b = new B();
A a2=b.x();
a2.z(); // Calling A class method without creating object of it
}
}
another example
class Person
{
private String lastName;
private String firstName;
private int age;
//--------------------------------------------------------------
public Person(String last, String first, int a)
{ // constructor
lastName = last;
firstName = first;
age = a;
}
//--------------------------------------------------------------
public void displayPerson()
{
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
//--------------------------------------------------------------
public String getLast() // get last name
{ return lastName; }
} // end class Person
////////////////////////////////////////////////////////////////
class ClassDataArray
{
private Person[] a; // reference to array
private int nElems; // number of data items
public ClassDataArray(int max) // constructor
{
a = new Person[max]; // create the array
nElems = 0; // no items yet
}
//--------------------------------------------------------------
public Person find(String searchName)
{ // find specified value
int j;
for(j=0; j<nElems; j++) // for each element,
if( a[j].getLast().equals(searchName) ) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return a[j]; // no, found it
} // end find()
//-------------------------------------------------------------- // put person into array
public void insert(String last, String first, int age)
{
a[nElems] = new Person(last, first, age);
nElems++; // increment size
}
//--------------------------------------------------------------
public boolean delete(String searchName)
{ // delete person from array
int j;
for(j=0; j<nElems; j++) // look for it
if( a[j].getLast().equals(searchName) )
break;
if(j==nElems) // can't find it
return false;
else // found it
{
for(int k=j; k<nElems; k++) // shift down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//--------------------------------------------------------------
public void displayA() // displays array contents
{
for(int j=0; j<nElems; j++) // for each element,
a[j].displayPerson(); // display it
}
//--------------------------------------------------------------
} // end class ClassDataArray
////////////////////////////////////////////////////////////////
class ClassDataApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ClassDataArray arr; // reference to array
arr = new ClassDataArray(maxSize); // create the array
// insert 10 items
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimson", "Henry", 29);
arr.insert("Velasquez", "Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);
arr.displayA(); // display items
String searchKey = "Stimson"; // search for item
Person found;
found=arr.find(searchKey);
if(found != null)
{
System.out.print("Found ");
found.displayPerson();
}
else
System.out.println("Can't find " + searchKey);
System.out.println("Deleting Smith, Yee, and Creswell");
arr.delete("Smith"); // delete 3 items
arr.delete("Yee");
arr.delete("Creswell");
arr.displayA(); // display items again
} // end main()
} // end class ClassDataApp
As in above code i am calling z() method of class A with reference a2 without creating object of class A,As i am new to java i want to know which concept is this in java in the shown code ? for now i just know that if we want to call a method without creating object of it we have to make that method as static .
in the second example using person reference found we are able to call displayPerson() method without null pointer exception
To call:
String z(){
System.out.println("a");
return "sauarbh";
}
without the object of the class A the method z has to be static:
static String z(){
System.out.println("a");
return "sauarbh";
}
So change your code as following:
class A{
static String z(){
System.out.println("a");
return "sauarbh";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner {
public static void main(String[] args) {
B b = new B();
b.x();
A.z();
}
}
Output :
a
Yes without instantiate the class if you want to call the method you should use static key word.
What are you doing here?
You are indirectly try to get instance of A. But this case you will get NullPointerException since you just return only a reference(variable) of A
B b = new B();
A a2=b.x();
a2.z(); // NullPointerException from here
NPE?
class B{
A a;
A x(){
return a; // you just return the reference
// it should be return new A();
}
}
For your edit:
Take a look at insert() method. It is creating Person instance.
Class B method x() is not returning new object of A. Instead you are returning object of Class A with null value.
A a; // value of a is null
A x() {
return a;
}
In runner class
A a2=b.x(); // b.x() will return a, which is null. so A a2=null
a2.z(); // Equivalent to null.z() throws NullPointerException
Make below changes in your Class B code:
class B{
A a;
A x(){
return new A();// return new object of Class A;
}
}
or
class B{
A a= new A(); // Initialize Class A with new object
A x(){
return a;
}
}
Related
I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}
The goal of my program is to store data for students(First Name, Last Name, ID#).I'm trying to create 4 Arrays. One array will hold the combined value of each student object that I'm adding(myDB). The other 3 hold indexes to the original spot of each value(Fname,Lname,ID) and add them to an ordered array without sorting the array. The trouble I'm having is that once I add something to the Index Arrays and go to print them, it prints all of the IDs regardless of what object I call.
//class containing methods to list, add, and delete
//Class that declares the main database array that holds all three (ID,First,Last)
import java.io.FileInputStream;
import java.util.*;
public class DataBase
{
private String tempID, tempFname, tempLname;
private DataBaseArray myDB;
private int nextDBRecord;
private IndexArray ID;
private IndexArray First;
private IndexArray Last;
public DataBase()
{
nextDBRecord = 0;
myDB =new DataBaseArray(100);
ID=(new IndexArray(100));
First=new IndexArray(100);
Last=new IndexArray(100);
}
void addData(String last, String first, String id)
{
tempLname = new String(last);
tempFname = new String(first);
tempID = new String(id);
//ID.insert(new IndexRecord(tempID, nextDBRecord));
First.insert(new IndexRecord(tempFname,nextDBRecord));
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));
System.out.println(myDB.getStudentArray()[nextDBRecord]);
nextDBRecord++;
}
void addIt ()
{
Scanner keyb = new Scanner(System.in);
System.out.println("Please enter the ID for new student entry");
tempID=keyb.next();
ID.insert(new IndexRecord(tempID, nextDBRecord));
System.out.println("Please enter the first name of the new student");
tempFname=keyb.next();
First.insert(new IndexRecord(tempFname, nextDBRecord));
System.out.println("Please eneter the last name of the new student");
tempLname=keyb.next();
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));;
nextDBRecord++;
}
void findIt()
{
}
void list (int type, int order)
{
First.printIt(order);
}
}
//Class that creates the objects to add to Iarray Farray Iarray
//IndexArray is a static array
//Creates a single entry into the IndexArray
//Need a compareTo method that gives the where value of each object
public class IndexRecord
{
private String key; //Value
private int where; //Where it is at in DataBaseArray
IndexRecord (String value, int position)
{
setKey(new String(value));
where = position;
}
public String toString()
{
return getKey()+" "+ String.valueOf(where);
}
public String getKey() //Getter for key value of the new student that is being added
{
return key;
}
public void setKey(String key) //Setter for key value of the new student that is being added
{
this.key = key;
}
}
//Same as OrderedArray Class
//Add Iterator methods. Instead of printing here, tell DataBase class what DatabaseRecord objects to print
public class IndexArray
{
private static IndexRecord[] irArray;
private int nOfElem; //Should be the same for each array so only 1 counter is needed
private int maxSize;
private int theIterator;
public IndexArray(int size)
{
nOfElem = 0;
maxSize=size;
irArray = new IndexRecord[size];
}
//-----------------------------Getters and Setters-------------------------------------
public int size() //Getter to find num of elements in array that can be called in other class
{ return nOfElem; }
public IndexRecord[] getIRarray()
{
return irArray;
}
//---------------------Iterator Methods-----------------------------------------------------
void iteratorToFront()
{
theIterator=(nOfElem>0? 0 : -1);
}
void iteratorToBack()
{
theIterator=(nOfElem>0 ? nOfElem-1 : -1);
}
boolean hasNext()
{
return (theIterator==nOfElem-1? false:true );
}
boolean hasPrevious()
{
return (theIterator==0? false : true);
}
public IndexRecord getIterator()
{
return(theIterator==-1 ? null :irArray[theIterator]);
}
int getNext()
{
theIterator=(hasNext()? theIterator+1: -1);
return(theIterator==-1? null : theIterator);
}
int getPrevious()
{
theIterator=(hasPrevious()? theIterator-1:-1);
return (theIterator==-1? null : theIterator);
}
//------------------Methods Called In Main---------------------------------------
public boolean insert(IndexRecord ir)
{
if(maxSize==nOfElem) return false;
int j;
for(j=nOfElem-1;j>=0;j--)
{
if(irArray[j].getKey().compareToIgnoreCase(ir.getKey())<0)break;
{
irArray[j+1]=irArray[j]; //Pushes all objects down to make room for new one
}
}
irArray[j+1]=ir;
nOfElem++;
return true;
}
public int find(String searchKey)
{
int lowerBound = 0;
int upperBound = nOfElem-1;
int currentRef;
while(true)
{
currentRef = (lowerBound + upperBound) / 2;
String tempValue = String.valueOf(irArray[currentRef].getKey());
if(tempValue.compareTo(searchKey) == 0)
return currentRef;
else if (lowerBound > upperBound)
return nOfElem; //returns a pointer to an empty slot
else
{
if(tempValue.compareTo(searchKey) > 0)
lowerBound = currentRef++;
else
upperBound = currentRef - 1;
}
}
}
//delete
public void printIt(int order)
{
switch(order)
{
case -1:
iteratorToBack();
break;
case 1:
iteratorToFront();
while(hasNext())
{
System.out.println(irArray[getNext()]);
}
break;
default:
}
}
}
for educational purposes I am trying to understand how to access a list's maximum element(originally in class B) (in this case from a Double list) through another class e.g class A. The list is used in a different class in which elements are added to it (e.g class C). However, when I add something like this to my class A to access my Max element, it does not seem to work: // help is appreciated :) and the error I usually get is noSuchElementException
just a method of class A
void printMax () {
B b = new B();
Double result;
result = Collections.max(b.array);
System.out.println("MAX:" +result);
}
here is my class B:
public class B {
public ArrayList<Double> array;
B() {
array = new ArrayList<Double>();
}
public void doSomething() {
int i;
for(i = 0; i < array.size(); i++) {
System.out.println("Doubles:" +array.get(i));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new B().doSomething();
}
}
Here is my class C that adds to my ArrayList.
Class C {
public String line;
C () {
}
public void linePicker() {
B b = new B();
Scanner dScanner = new Scanner(line);
while (dScanner.hasNext()) {
if (dScanner.hasNextDouble()) {
b.array.add(dScanner.nextDouble());
break;
} else {
dScanner.next();
}
}
dScanner.close();
b.doSomething();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new C().linePicker();
}
}
According to the javadocs (http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection,%20java.util.Comparator)), it throws that exception when the Collection is empty. You initialize b.array, but haven't added to it yet before calling max().
I am attempting to construct a list of rows which contain cells. The classes row and cell have been defined.
I want to construct the array list and then print it.
My Code:
import java.util.*;
public class findBfs
{
int numWarehouses;
int numCustomers = 4;
ArrayList<Integer[]> warehouses = new ArrayList<Integer[]>();
Integer[] warehouse1 = {3,6,8,2};
Integer[] warehouse2 = {6,1,2,5};
Integer[] warehouse3 = {7,8,3,9};
class Cell {
int cost;
int shipment;
public Cell(int x, int y){
x = cost;
y = shipment;
}
public int getCost(){
return cost;
}
public int getShipment(){
return shipment;
}
public void updateShipment(int newAmount){
shipment = newAmount;
}
}
class Row{
public Row(Integer[] warehouse) {
ArrayList<Cell> row = new ArrayList<Cell>();
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
ArrayList<Row> tableu = new ArrayList<Row>();
public findBfs()
{
warehouses.add(warehouse1);
warehouses.add(warehouse2);
warehouses.add(warehouse3);
for(Integer[] thisWarehouse : warehouses)
{
tableu.add(new Row(thisWarehouse));
}
}
public void printTableu() {
for(Row thisRow : tableu) {
System.out.println(thisRow);
}
}
}
Currently with the code I have the following gets printed:
findBfs$Row#25ca623f
findBfs$Row#9f8297b
findBfs$Row#36b4f5a
What has happened? :(
You have declared row ArrayList<Cell> type as local to the constructor. Declare it in your class context: which is probably you are wanting.
override the toString() method and provide an implementation in the Row class with proper format you want it to see as String. You will probably need to override toString() method and provide an implementation for the Cell class too.
For a List of specific element, i prefer to declare the list with the element name as prefix and list as suffix: suppose instead of ArrayList<Cell>row, declare it as ArrayList<Cell>cellList
For example:
class Cell {
// your other code
#Override
public void String toString() {
return "shipment: " + shipment + "; cost: " + cost;
}
}
class Row{
ArrayList<Cell> cellList = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse)
cellList.add(new Cell(value, 0));
}
#Override
public void String toString() {
return cellList.toString();
}
}
Edit:
you are assigning the class variable wrongly, constructor_local_var <- class_var: which should be class_var <-- constructor_local_var
public Cell(int x, int y){
cost = x;
shipment = y;
}
class Row{
ArrayList<Cell> row = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
i think doing this and overriding toSting() will help
When an object is printed out, it is converted to a String first, using the toString() method. Since you did not override it, you're getting the default implementation from Object, which, as you can see, is pretty useless.
You should just override it, like you override any other method. E.g.:
class Cell {
// snipped
#Override
public void String toString() {
return "Cell [shipment: " + shipment + "; cost: " + cost + "]";
}
}
class Row {
// snipped
#Override
public void String toString() {
// row.toString() could be simpllified to row - added for clarity.
return "Row: " + row.toString();
}
}
You need to save the warehouse or the row variable in the Row class, depending on what you want to print, and then override the toString() method.
Following is an example implementation of the Row class for the warehouse version.
class Row {
private Integer[] warehouse;
public Row(Integer[] warehouse) {
this.warehouse = warehouse;
ArrayList<Cell> row = new ArrayList<Cell>();
for (int value : warehouse) {
row.add(new Cell(value, 0));
}
}
public String toString() {
return Arrays.asList(this.warehouse).toString();
}
}
Lets say I have three classes:
Class A:
public class A {
private String s;
public A() {
s = "blah";
}
public void print() {
System.out.println(s);
}
}
Class B:
public class B{
private A a[];
public B(){
a = new A[100];
for (int i=0; i<100;i++) {
a[i] = new A();
}
}
public void print() {
for (int i=0; i<100; i++) {
a.print(); //SHOULD BE a[i].print();
}
}
}
Class Main:
public class Main {
public static void main(String args[]) {
B b = new B();
b.print();
}
}
Why do I get an outputpattern like B##, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s?
You are printing the array rather than the object in the array. As a result, it is printing the address of the object (the number) and the object it is a member of.
I suspect you wanted to call each of the prints, you should, in B.print(). You are also missing an increment for i, meaning it will loop indefinitely.
for(int i = 0; i < 100; ++i)
{
a[i].print();
}