/**
* Created by unibodydesignn on 11.03.2017.
*/
public interface Enumeration
{
// Returns true if another element in the collection exists
public boolean hasNext();
// Returns the next element in the collection as an Object
public Object getNext(); }
/**
* NameCollection implements a collection of names using
* a simple array.
*/
public class NameCollection
{
String[] names;
//this array will be initiliazed at outside
NameCollection(String[] names)
{
this.names = names;
}
/**
* getEnumeration should return an instance of a class that
implements
* the Enumeration interface where hasNext() and getNext()
* correspond to data stored within the names array.
*/
Enumeration getEnumeration ()
{
}
public boolean hasNext()
{
//i will define this method here
}
public Object getNext()
{
//i will define getNext() here
}
Complete the method getEnumeration() so that it returns an anonymous inner class that corresponds to the Enumeration interface for the names array in
NamesCollection. Then write a main method that creates a NamesCollection
object with a sample array of strings, retrieves the Enumeration for this class via
getEnumeration(), and then iterates through the enumeration outputting each
name using the getNext() method.
I don't understand this question's concept. I clearly do not know what to do or where to start? Can I find Java's default hasNext() definition?
It is not homework.
It is a programming project from Absolute Java book. Chapter 13. P3.
Complete the method getEnumeration() so that it returns an anonymous inner class that corresponds to the Enumeration interface for the names array in NamesCollection.
The purpose of the exercise seems to be working with anonymous classes.
For example, instead of creating a named class like this:
class NamesEnumeration implements Enumeration {
#Override
public boolean hasNext() {
// ...
}
#Override
public Object getNext() {
// ...
}
}
... the instructions guide you to use an anonymous class instead, like this:
Enumeration getEnumeration() {
return new Enumeration() {
#Override
public boolean hasNext() {
// ...
}
#Override
public Object getNext() {
// ...
}
};
}
An important point is that anonymous implementation can use variables visible in its scope. Most notably for this example,
the names field of the enclosing NamesCollection class.
In the NamesCollection class,
you don't need the hasNext and getNext methods.
So the class should look something like this:
public class NameCollection {
final String[] names;
NameCollection(String[] names) {
this.names = names.clone();
}
Enumeration getEnumeration() {
return new Enumeration() {
int currentIndex = 0;
// ^^^^^^^^^^^^ this is a hint for you
#Override
public boolean hasNext() {
// ...
}
#Override
public Object getNext() {
// ...
}
};
}
}
I've made some minor improvements, and added a hint to help you complete the implementation.
Lastly, the exercise also asks to add a main method to exercise this class. That should be something like this:
public static void main(String[] args) {
String[] sample = {"hello", "world"};
NameCollection namesCollection = new NameCollection(sample);
Enumeration names = namesCollection.getEnumeration();
while (names.hasNext()) {
System.out.println(names.getNext());
}
}
i dont know about that book you say, but lets understand what is requested:
What you need to do is create an implementation of the Enumeration Interface, i dont know if this chapter is about Interfaces, or Enumarations.
1: "Complete the method getEnumeration() so that it returns an anonymous inner class that corresponds to the Enumeration interface for the names array in NamesCollection".
Here you need to return an implementation of the Enumeration interface, the question says to create an Anonymous class (but i sugest to create an Inner Class, maybe Private Inner Class). like this, inside the NameCollection class:
public Enumeration getEnumeration(){
Enumeration enumerat = new Enumeration(){
private int index = 0;
public boolean hasNext(){
return names.length > index;
}
public Object getNext(){
return names[index++];
}
};
return enumerat;
}
The method returns an implementation of the Enumeration class that you can use to traverse throught the array of names you passed to the constructor of the NameCollection class.
2: "Then write a main method that creates a NamesCollection object with a sample array of strings, retrieves the Enumeration for this class via getEnumeration(), and then iterates through the enumeration outputting each name using the getNext() method".
Here you just need to create a test class for your implementation:
public class Main {
public static void main(String[] args) {
NameCollection nc = new NameCollection(new String[]{ "Adriane", "Beatriz" });
Enumeration en = nc.getEnumeration();
while( en.hasNext() ){
System.out.printf("Name: %s \n", en.getNext() );
}
}
}
Related
Here's an example:
class A
{
List l = new List ();
list.insert("x");
}
class List
{
...
public void insert ()
{
/*insertion occurs*/
}
...
}
Is it possible at all to keep the insert() method public, but limit access only to class A so that no other class can access it, only when called from A?
I would pass the object that is calling the method as an argument, i.e.
list.insert("x", this);
And then check if the passed Object is an Instance of Class A
public void insert (String x, Object o)
{
if(o instanceof ClassA){
/*insertion occurs*/
}
}
If the method is public, everyone can access it. The trick to access control like yours is to expose a set of public operations through an interface, add auxiliary operations to a private class implementing the interface, and make your users program to the interface, not to a class.
Here is an example:
public interface MyList {
Object elementAt(int i);
}
public class A {
private static class MyListImpl implements MyList {
public Object elementAt(int i) {
...
}
public void insert(Object element) {
...
}
}
private final MyListImpl list = new MyListImpl();
public MyList getList() { return list; }
public void insert(Object o) { list.insert(o); }
}
Usage scenario:
A a = new A();
a.insert(123);
a.insert("quick brown fox");
MyList lst = a.getList();
System.out.println(lst.elementAt(0));
System.out.println(lst.elementAt(1));
Yes, you can pass calling object as an argument and put a check in insert() method before actual code.
public void insert(Object obj){
if(obj instanceof A){
//your code block
}
}
Please note that this will allow all the classes that extends A as well to call insert. If you want to restrict only for class A, add additional check.
public void insert(Object obj){
if((obj instanceof A) && obj.getClass().getSimpleName().equals("A")){
//your code block
}
}
we can also achieve second case with only condition "obj.getClass().getSimpleName().equals("A")" as well.
The best you can do using access modifiers is to make the method package private (remove the public keyword) and keep only those two classes in the same package.
If all the "inner classes" stuff in the previous answers confuses you, there is another way that may be more intuitive (assuming you've learned about the extends keyword and inheritance). You can simply make the insert() method protected instead of public and make class A extend List. For example:
public class List {
...
protected void insert() {
//insertion occurs
}
...
}
public class A extends List {
...
}
As long as no other classes extend List, only objects of types A and List will ever be able to use the insert() method.
package problems;
public class Problem1 {
public static void main(String[] args) {
B b = new B();
b.methodInB();
C c = new C();
c.methodNotInB();
}
}
class A {
public void onlyB() {
StackTraceElement[] stackTraceElements = Thread.currentThread()
.getStackTrace();
if (!problems.B.class.getCanonicalName().equals(
stackTraceElements[stackTraceElements.length - 2]
.getClassName())) {
System.err.println("You are not authorized to call me!!");
return;
}
System.out.println("You are authorized to call me!!");
}
}
class B {
public void methodInB() {
A a = new A();
a.onlyB();
}
}
class C {
public void methodNotInB() {
A a = new A();
a.onlyB();
}
}
Put it as inner class in A or you can do another thing ...
Let insert takes one parameter with type of Object and in the beginning of it check if the parameter's type is A .... and when you call it send the calling object...
maby its not a good idea but it will do what you want
Put it into the permitted class and make it private.
I'm converting a project from Java to C#. In this Java project, there is an interface: public interface TrackIterator, then it as a member in it: public Iterator createIterator();. The class that is going to implement it has createIterator as a method which returns an Arraylist of objects (in C# List),How would I convert this from Java to C# so I can implement it on a converted C# class
// interface
public interface TrackIterator
{
public Iterator createIterator();
}
// class that implements it
public class trackList implements TrackIterator
{
// other methods, fields, etc
// method from interface TrackIterator
public Iterator createIterator()
{
// popularSongs is an ArrayList of objects in Java, in C# it's a List<MyTrack>
return popularSongs.iterator();
}
}
The way I see it, you can go about this in two ways. The first would be to make TrackList implement IEnumerable<Track>, and roll your own enumerable:
public class Track
{
public bool IsGoodTrack => true;
}
public class TrackList : IEnumerable<Track>
{
private List<Track> tracks = new List<Track>();
public IEnumerator<Track> GetEnumerator()
{
// Implement custom logic here.
foreach (var track in tracks)
{
if (track.IsGoodTrack())
yield return track;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Or, if there's no kind of special logic over exposing a List<Track>, simply use a List<Track> wherever you need one:
public class Foo
{
// Foo has a `List<Track>` property:
public List<Track> Tracks { get; } = new List<Track>();
}
In case you just want to get a list with tracks and print them to the console, it is as simple as:
var listOfTracks = new List<Track>();
foreach (var track in listOfTracks)
{
Console.WriteLine(track);
}
I'm building a base/parent class in Java that's going to have several methods for creating the class itself and I'm wondering if there's any way to have the parent class return instances of the child class instead of returning instances of the parent class that then have to be cast to the child?
For example, here's my parent class:
public abstract class SFObject
{
// Variables
protected String mID;
protected String mName;
// Function called to create ourselves from a DiffObject
public abstract SFObject CreateFromDiffObject(DiffObject object);
// Function called to create a list of ourselves from a query
public List<SFObject> CreateListFromQuery(Connection connection, String query)
{
// Run the query and loop through the results
ArrayList<SFObject> objects = new ArrayList<SFObject>();
for (DiffObject object : connection.Query(query))
objects.add(CreateFromDiffObject(object));
return objects;
}
}
If I create a child class based on my SFObject class, the two functions in my child class will still return an SFObject (that needs to be cast to my child class type) or a list of SFObjects (that need to be individually cast to my child class type). Is there any way (maybe using Reflections) to have my child class returns instances of itself as itself and not as SFObjects?
What you are describing is known as a covariant return type.
Class A {
A getInstance() { ... }
}
Class B extends A {
#Override
B getInstance() { ... }
}
This has been allowed since Java 1.5.
If you place the child class object inside of the parent object, methods called will run from the child class. But it will look like the parent object on the surface
public class A{
method 1(){//do some stuff}
method 2(){//do some stuff}
}
public class B extends A{
method 1(){super.method 1()
//do some other stuff}
method 2(){super.method 2()
//do some other stuff}
}
public class test{
A a = new B();
//any method called on 'a' will come from the child class
// But 'a' is the parent object
}
Not sure if I really understand your Problem correct because it sounds to me lke this:
class p
{
public static p createParent()
{
return new p();
}
public static c createChild()
{
return new c();
}
}
Of course it doesn't have to be static, just thought of some kind of factory.
Exactly for this functionalities are proposed the factory methods, as you already implemented. In the child class you can change the return type without offending the method declaration. A sample for your case would be something like:
public abstract class SFObject {
// Variables
protected String mID;
protected String mName;
// Function called to create ourselves from a DiffObject
public abstract SFObject CreateFromDiffObject(DiffObject object);
// Function called to create a list of ourselves from a query
public List<? extends SFObject> CreateListFromQuery(Connection connection, String query) {
// Run the query and loop through the results
ArrayList<SFObject> objects = new ArrayList<SFObject>();
for (DiffObject object : connection.Query(query))
objects.add(CreateFromDiffObject(object));
return objects;
}
}
class SFObjectChild extends SFObject {
#Override
public SFObjectChild CreateFromDiffObject(DiffObject object) {
SFObjectChild result = new SFObjectChild();
//...
return result;
}
#Override
public List<? extends SFObjectChild> CreateListFromQuery(Connection connection,
String query) {
return null;//..;
}
}
This is acceptable because the return type of the children class is still a kind of (hierarchical speaking) the parent.
Be aware of java code conventions (methods in camel case starting with low, e.g. createFromDiffObject).
Here's an example:
class A
{
List l = new List ();
list.insert("x");
}
class List
{
...
public void insert ()
{
/*insertion occurs*/
}
...
}
Is it possible at all to keep the insert() method public, but limit access only to class A so that no other class can access it, only when called from A?
I would pass the object that is calling the method as an argument, i.e.
list.insert("x", this);
And then check if the passed Object is an Instance of Class A
public void insert (String x, Object o)
{
if(o instanceof ClassA){
/*insertion occurs*/
}
}
If the method is public, everyone can access it. The trick to access control like yours is to expose a set of public operations through an interface, add auxiliary operations to a private class implementing the interface, and make your users program to the interface, not to a class.
Here is an example:
public interface MyList {
Object elementAt(int i);
}
public class A {
private static class MyListImpl implements MyList {
public Object elementAt(int i) {
...
}
public void insert(Object element) {
...
}
}
private final MyListImpl list = new MyListImpl();
public MyList getList() { return list; }
public void insert(Object o) { list.insert(o); }
}
Usage scenario:
A a = new A();
a.insert(123);
a.insert("quick brown fox");
MyList lst = a.getList();
System.out.println(lst.elementAt(0));
System.out.println(lst.elementAt(1));
Yes, you can pass calling object as an argument and put a check in insert() method before actual code.
public void insert(Object obj){
if(obj instanceof A){
//your code block
}
}
Please note that this will allow all the classes that extends A as well to call insert. If you want to restrict only for class A, add additional check.
public void insert(Object obj){
if((obj instanceof A) && obj.getClass().getSimpleName().equals("A")){
//your code block
}
}
we can also achieve second case with only condition "obj.getClass().getSimpleName().equals("A")" as well.
The best you can do using access modifiers is to make the method package private (remove the public keyword) and keep only those two classes in the same package.
If all the "inner classes" stuff in the previous answers confuses you, there is another way that may be more intuitive (assuming you've learned about the extends keyword and inheritance). You can simply make the insert() method protected instead of public and make class A extend List. For example:
public class List {
...
protected void insert() {
//insertion occurs
}
...
}
public class A extends List {
...
}
As long as no other classes extend List, only objects of types A and List will ever be able to use the insert() method.
package problems;
public class Problem1 {
public static void main(String[] args) {
B b = new B();
b.methodInB();
C c = new C();
c.methodNotInB();
}
}
class A {
public void onlyB() {
StackTraceElement[] stackTraceElements = Thread.currentThread()
.getStackTrace();
if (!problems.B.class.getCanonicalName().equals(
stackTraceElements[stackTraceElements.length - 2]
.getClassName())) {
System.err.println("You are not authorized to call me!!");
return;
}
System.out.println("You are authorized to call me!!");
}
}
class B {
public void methodInB() {
A a = new A();
a.onlyB();
}
}
class C {
public void methodNotInB() {
A a = new A();
a.onlyB();
}
}
Put it as inner class in A or you can do another thing ...
Let insert takes one parameter with type of Object and in the beginning of it check if the parameter's type is A .... and when you call it send the calling object...
maby its not a good idea but it will do what you want
Put it into the permitted class and make it private.
I have the following code
public class A extends Iterable<Integer> {
...
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
A a;
public boolean hasNext() {
...
}
public Integer next() {
...
}
public void remove(){
...
}
};
I would like to initialize the "a" field in the anonymous class with the instance of A that iterator method was called on. Is it possible?
Thank you.
You don't need to.
You can call methods on the outer class normally within the inner class.
When you compile it, the compiler will automatically generate a hidden field that contains a reference to the outer class.
To reference this variable yourself, you can write A.this. (A.this is the compiler-generated field and is equivalent to your a field)
Try this:
public class A extends Iterable<Integer> {
public Iterator<Integer> iterator() {
final A a = this;
return new Iterator<Integer>() {
public boolean hasNext() {
// here you can use 'a'
}
}
}
}
Use :
A a = A.this