Java How do I create an instance of a class in a method using Java?

Click For Summary
To create an instance of a class within a method, particularly when dealing with an abstract class like School, it's essential to understand that abstract classes cannot be instantiated directly. Instead, a concrete subclass must be derived from the abstract class. The discussion emphasizes the use of constructors, particularly when the abstract class has multiple parameters. The method Constructor.newInstance() is highlighted as a way to instantiate the subclass, but it requires the subclass to be defined first. The confusion arises from the common association of instances with the main method, but instances can also be created in other methods as long as they are derived from a concrete implementation of the abstract class. For further clarification, resources on Java's abstract classes and reflection are recommended.
Robben
Messages
166
Reaction score
2

Homework Statement



How do I create an instance of a class in a method?

Homework Equations



None

The Attempt at a Solution



I am a bit rusty whenever I think of instances. I always think of main method and objects when I see instance which gets me confused on what to do with the following example:

I have a abstract class, School, and inside School I have some methods that must preform some action on an instance. For example, there is a move() method that must move the instance of School. Another method named, personOld(), which returns whether or not an instance of School surpassed some determined age.
How do I create this instance?
 
Last edited:
Technology news on Phys.org
Greg Bernhardt said:

Hm, in those examples they put the objects in the main method which is what I always think of when I see instance, but I have a class which isn't a main method which is what has gotten me confused.

Since my constructor, in my abstract School class, has many parameters then I must Constructor.newInstance()?

But how do I apply this?
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 25 ·
Replies
25
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 9 ·
Replies
9
Views
1K
  • · Replies 3 ·
Replies
3
Views
6K
  • · Replies 23 ·
Replies
23
Views
2K
Replies
2
Views
2K
Replies
3
Views
3K
  • · Replies 14 ·
Replies
14
Views
5K
  • · Replies 3 ·
Replies
3
Views
1K