So I have a concrete class and an abstract class and I am trying to access methods from the concrete class from the abstract one. Store currently contains many getters that the member class needs. Currently get null pointer exception.
public abstract class members{
// Trying to refrence the store object
Store store;
public void someMethod(){
// I want to be able to access all the methods from the store class
// eg
store.showVideoCollection();
}
}
public class store {
// This class has already been instantiated, just one object for it.
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
EDIT:
In the main method
public class start {
public start() {
store = new Store(); // Don't want to create more than 1 store object.
}
Thanks
In order to store a Store instance you must instantiate it. As is, you declare the variable store but you never initialize it (so it's null). I think you wanted something like
// Trying to refrence the store object
Store store = new Store(); // <-- create a Store and assign it to store.
Alternatively, you could make Store a Singleton. The linked Wikipedia page says (in part) the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
public final class Store {
public static Store getInstance() {
return _instance;
}
private static final Store _instance = new Store();
private Store() {
}
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
Related
I'm trying to instantiate an object inside a method of a class so it can be used anywhere in the class. I come from a python background and it is quite easy, you can just pass the instantiated object to an instance of it's "self" like below.
self.camera = CameraInstance()
How do you do this in Java? I tried something like below but it doesn't like it.
private void init_camera_settings() {
public CameraInterface camera;
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
Both methods are in the same class. The reason for this is because I only want to instantiate the camera object only in certain scenarios.
Thanks!
You can't declare a field inside a method. In Java, a type either has a field, or it doesn't. Every instance of the same class has the same set of fields.
But you can declare the field (not in a method) and decide to only assign a value to it in a method:
// Note: avoid public fields
public CameraInterface camera;
private void initCameraSettings() {
camera = new Camera();
}
private void someotherMethod() {
camera.takePhoto();
}
(The field will have a default value, in this case null, until you assign a different value to it.)
As an aside, I'd strongly advise against public fields. I make every field private, and add properties to allow access where necessary. This allows you to change implementation details later. The one exception to this is public static final fields of immutable types, basically for constants, but even there I'd be cautious.
To use the variable throughout the class in different methodsm the variables should have class scope. You usually use new to create a new Object
public MyClass {
public CameraInterface camera = new Camera ();
private void init_camera_settings() {
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
}
self.camera = CameraInstance()
is equivalent to:
class Foo {
private CameraInstance camera;
public Foo() {
this.camera = new CameraInstance();
}
// use "this.camera" in methods.
}
I want to create an object that is linked in some way to another object of the same class. This link should be specified in the constructor of the new object.
public class Counter {
public Counter(){
// default counter constructor
}
public Counter(Counter oldCounter){
// do stuff specifying new object is linked to oldCounter
}
public void someMethod(){
// this method should call a method belonging to oldCounter
oldCounter.someOtherMethod();
}
Tried searching the archives for an answer, but couldn't find anything...
Remember the argument as a private instance member, then use that member:
public class Counter {
// The instance member we'll use, note that we initialize it to `null`
// because you have a zero-args constructor, so we want to be sure we
// know whether we have one or not
private Counter otherCounter = null;
public Counter() {}
public Counter(Counter oldCounter) {
// Remember it here
this.otherCounter = oldCounter;
}
public void someMethod() {
// Use it here
if (this.otherCounter != null) {
this.otherCOunter.someOtherMethod();
}
}
}
To achieve what you want Crowder's answer is good enough.
You are having two version of same class. For me it seems that you need to follow some design pattern to better organize your code. In this case Factory Pattern may be a good choice.
I've been trying to code something so that:
Class 1 creates an instance of Class 2 (Class t = new Class() ). That instance can be used in Class 1,2 and 3.
I've been looking around for a bit and found the "Singleton Pattern". I don't understand how I implement this into my code though and a fair few of the sources are all saying different things...
Thanks for any help, much appreciated :)
Singleton Example: If you have a Class Phonebook and you want every Class of your programm refer to the same Phonebook. You would make the Class Phonebook a Singleton-Class.
In other words: The Singleton Pattern is used, to asure every other Code is refering to the same Object of the Singleton-Class.
class Phonebook {
//Make the constructor private so no one can create objects, but this class
private Phonebook() {
}
// to static members to hold (m_Instance) and get (getInstacnce) the Singleton Instance of the class
private static Phonebook m_Instance;
public static Phonebook getInstance() {
if (m_Instance == null) {
// first call to getInstance, creates the Singelton Instance, only we (Phonebook) can call the constructor;
m_Instance = new Phonebook();
}
return m_Instance; //always the same Instance of Phonebook
}
... // Members of the Phonebook (add/getPhoneNumber)
}
Every part of the software, will get the same Instance of the Phonebook. So we can register phonenumbers, every other class can read.
...
Phonebook l_Phonebook = Phonebook.getInstance();
l_Phonebook.addPhoneNumber("Yoschi", "01774448882")
...
// somewhere else
Phonebook l_Phonebook = Phonebook.getInstance();
Phone.getInstance().call(l_Phonebook.getPhoneNumber("Yoschi"));
Here is a link to the description:
http://en.wikipedia.org/wiki/Singleton_pattern
A sample code will be
public class singleton
{
public static singleton _obj;
private singleton()
{
// prevents instantiation from external entities
}
public static singleton GetObject() // instead of creating new operator, declare a method and that will create object and return it.
{
if (_obj == null) //Checking if the instance is null, then it will create new one and return it
//otherwise it will return previous one.
{
_obj = new singleton();
}
return _obj;
}
public void printing(string s)
{
Console.WriteLine(s);
}
}
This is a c# code but the concepts are the same as java.
I have got some methods that are common to two subclasses so i have put them in Abstract superclass but there is one method that uses a variable with two different values so i am confused how to implement that method the code is like:
StandardMember class got this method with its own different value for remainingCredit=30 at starting
public void borrowHolding(int holdingId)
throws InsufficientCreditException, MultipleBorrowingException {
// TODO Auto-generated method stub
System.out.println("Hello");
Holding tempHolding = Library.libCollection.getHolding(holdingId);
if (Library.libCollection.getHolding(holdingId) != null) {
if (tempHolding.isOnLoan()) {
System.out.println("Can not be issued Currently on Load");
} else {
System.out.println("Can be issued");
remainingCredit-=tempHolding.getDefaultLoanFee();
System.out.println(getRemainingCredit());
tempHolding.setLoanCheck(true);
currentlyBorrowedHolding.put(holdingId, tempHolding);
System.out.println(remainingCredit);
System.out.println(holdingId);
}
}
PremiumMember Class got same method but the value of remainingCredit is 45, Whereas all the methods common to them are implemented in this AbstractMember class which implements the Member interface. but when i try to call these method from other class i have to initialize the object of AbstractMember in Library Class like this
Member member = new StandardMember();
which is very bad because I can not use the StandardMember object to run the PremiumMember Object's version of same method. so, either i should create new object of PremiumMember Class or i dont know what to do. but if i create two objects then this member object is being used in borrowHolding method which is basically a cascading method in Library Class which in turn calls the borrowHolding method in Member Interface:
public void borrowHolding(int holdingId) throws InsufficientCreditException, MultipleBorrowingException {
if(libCollection.holdingMap==null){
System.out.println("Collection is Empty");
}
if(libCollection.holdingMap.containsKey(holdingId))
member.borrowHolding(holdingId);
}
the problem is i can not create two objects because at runtime i can only call one method. so help me out how to implement this method in Abstract class so that program will detect the difference that which object it should create.
If I understood you correctly, you have a Member abstract class with a field remainingCredit which has to be 30 in one subclass and 45 in another.
Use a protected constructor.
public abstract class Member {
private int remainingCredit;
// Other members
// getters and setters
protected Member(String memId, String memName, int remainingCredit) {
this.memId = memId;
this.memName = memName;
this.remainingCredit = remainingCredit;
}
}
public StandardMember extends Member {
public StandardMember(String memId, String memName) {
super(memId, memName, 30);
}
}
public PremiumMember extends Member {
public PremiumMember(String memId, String memName) {
super(memId, memName, 45);
}
}
Is it possible to get the class type from inside the static initialization block?
This is a simplified version of what I currently have::
class Person extends SuperClass {
String firstName;
static{
// This function is on the "SuperClass":
// I'd for this function to be able to get "Person.class" without me
// having to explicitly type it in but "this.class" does not work in
// a static context.
doSomeReflectionStuff(Person.class); // IN "SuperClass"
}
}
This is closer to what I am doing, which is to initialize a data structure that holds information about the object and its annotations, etc... Perhaps I am using the wrong pattern?
public abstract SuperClass{
static void doSomeReflectionStuff( Class<?> classType, List<FieldData> fieldDataList ){
Field[] fields = classType.getDeclaredFields();
for( Field field : fields ){
// Initialize fieldDataList
}
}
}
public abstract class Person {
#SomeAnnotation
String firstName;
// Holds information on each of the fields, I used a Map<String, FieldData>
// in my actual implementation to map strings to the field information, but that
// seemed a little wordy for this example
static List<FieldData> fieldDataList = new List<FieldData>();
static{
// Again, it seems dangerous to have to type in the "Person.class"
// (or Address.class, PhoneNumber.class, etc...) every time.
// Ideally, I'd liken to eliminate all this code from the Sub class
// since now I have to copy and paste it into each Sub class.
doSomeReflectionStuff(Person.class, fieldDataList);
}
}
Edit
I picked the accepted answer based on what applied best to my problem, however it seems to me that all three of the current answers have their merits.
No, it's not possible without grabbing the stacktrace (which is imo nastier than your initial approach and for which I would in any way prefer Thread#getStackTrace() above new Exception()).
Rather do that job in a non-static initializer (or the default constructor) of the abstract class where you check the initialized status.
public abstract class SuperClass {
{
if (!isInitialized(getClass())) {
initialize(getClass());
}
}
}
The called methods in turn can be safely static.
yes, I use this often to initialize a static Log variable :
e.g. :
public class Project implements Serializable, Cloneable, Comparable<Project> {
private static final Logger LOG = LoggerFactory.getLogger(Project.class);
...
To get a class at runtime, you could do something along the lines of
public class Test {
public static void main(String[] args) {
try{
throw new Exception();
}
catch(Exception e){
StackTraceElement[] sTrace = e.getStackTrace();
// sTrace[0] will be always there
String className = sTrace[0].getClassName();
System.out.println(className);
}
}
}
Not pretty but will do the job (ripped from http://www.artima.com/forums/flat.jsp?forum=1&thread=155230).
This means you still make a call from the subclass (so is in the stack trace), but you don't need to include the XXX.class as an argument.