I was studying livewallpaper in this site. However something there is something that i dont understand.
Example in the code of the tutorial there a class named MyPoint
public class MyPoint {
String text;
private int x;
private int y;
public MyPoint(String text, int x, int y) {
this.text = text;
this.x = x;
this.y = y;
}
}
then after he created a MyWallpaperService class. Inside of that class there is a line of code like this
private List<MyPoint> circles;
private Paint paint = new Paint();
private int width;
int height;
private boolean visible = true;
private int maxNumber;
private boolean touchEnabled;
public MyWallpaperEngine() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(MyWallpaperService.this);
maxNumber = Integer
.valueOf(prefs.getString("numberOfCircles", "4"));
touchEnabled = prefs.getBoolean("touch", false);
circles = new ArrayList<MyPoint>();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
handler.post(drawRunner);
}
You can see the part of code has
private List<MyPoint> circles;
This is the part that i dont understand? What is happening in here? What will List<MyPoint> pass in the circles? Anyone knows what to call this? is this list reffering to a class? Cause im not sure on my title. Thank you..
private List<MyPoint> circles;
States that circles is a List of type MyPoint, (ie. it will hold objects of type MyPoint).
circles = new ArrayList<MyPoint>();
Now in the above line you are assigning the ArrayList object of type MyPoint to the Object Reference Variable of type List.
This is called as Interface Polymorphism.
List is an Interface, where as ArrayList a Concrete Class which implements List.
Eg:
public class Dog{
private String dName;
priavet int dAge;
public Dog(String dName, String dAge){
this.dName = dName;
this.dAge = dAge;
}
public String getDName(){
return this.dName;
}
public String getDName(){
return this.dAge;
}
}
public class Test{
public static void main(String[] args){
List<Dog> dAList = new ArrayList<Dog>();
dAList.add(new Dog("Tommy",5));
dAList.add(new Dog("Stark",2));
for(Dog d : dAList){ // Iterating over the List of Dog objects
System.out.println(d.getDName());
System.out.println(d.getDAge());
}
}
}
The List<MyPoint> object is, as the name suggests, a list of MyPoint instances which, judging from the code, represent the centers of your circles. The private identifier simply indicates that it cannot be accessed from outside of the class in which it is defined.
Its creating a list of objects. A List of MyPoint type objects
MyPoints in your case refers to the (x,y) coordinates of the circle(as you referred)
Related
In my current programming project I have some basic classes, like Numbers or ImageSets. In other classes I use these to display Information. I thought the easiest way (not so much coding) is to let the Display-Classes extend the base-Classes.
But at one Class (TwoDigits) I need two instances of the superclass (ImageSet). Is this possible? Normally you would call super(), but a second super() call is not allowed...
Here is some code of the Number-Class: (Element is another abstract selfmade class)
public class ImageSet extends Element{
private int x;
private int y;
private int imageIndex;
private int imagesCount;
public ImageSet(int x,int y,int imageIndex,int imagesCount, boolean ignoreDimension) throws IOException, UnequalDimensionsException {
if(!ignoreDimension) {
[...]//Check for equal Dimensions, otherwise throw UnequalDimensionsException
}
this.x=x;
this.y=y;
this.imageIndex=imageIndex;
this.imagesCount=imagesCount;
}
[...]
}
Here is some code from the Base-Class (TwoDigits):
public class TwoDigits extends Element{
ImageSet tens;
ImageSet ones;
Dimension d = null;
public TwoDigits(int x, int y, int imageIndex, int imageCount, boolean ignoreDimension) throws UnequalDimensionsException, IOException{
tens = new ImageSet(x,y,imageIndex,imageCount,ignoreDimension);
String imageIndexFormatted = String.format("%04d", imageIndex);
d = StaticHelpers.getImageDimension(new File("data/"+imageIndexFormatted+".png"));
ones = new ImageSet(x+d.width,y,imageIndex,imageCount,ignoreDimension);
}
[...]
}
I would like to change the SuperClass of TwoDigits to ImageSet to save some code in other classes.
Thanks for any help.
I have the following:
public class ExampleObject extends GridObject {
private static Context c;
private static final String name = "Example Object";
private static Bitmap skin = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject );
private static float x,y;
public ExampleObject(Context c, float x, float y) {
this.c = c;
this.x = x;
this.y = y;
}
}
The class has 3 static class members, The image is a decoded bitmap, I want it to be decoded once and once only for use on ALL instances of this object.
In it's current state is this achieved? or is it decoded every time an instance of this class is created?
How should it be done?
A static field will only be initialized once; this is guaranteed by the JLS.
However, the decodeResource method will be called when the class is initialized, at which point your Context is null, so it will fail. You'll need something more complex if you want a static field which is only initialized once; something a bit closer to a singleton.
public class ExampleObject extends GridObject {
private static final String name = "Example Object";
private static Bitmap skin;
// = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject );
private static float x,y;
public ExampleObject(Context c, float x, float y) {
synchronized(ExampleObject.class) {
if(skin == null) {
skin = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject);
}
}
this.x = x;
this.y = y;
}
}
You can achieve your intended behavior by the following class definition.
public class ExampleObject extends GridObject {
private static Bitmap skin;
public static Bitmap getSkin(Context c){
if(skin == null){
skin = BitmapFactory.decodeResource( c.getResources(), R.drawable.defaultObject );
}
return skin;
}
}
Static variables are initialized only once and A single copy of it is to be shared by all instances of the class.
This single initialization procedure is run automatically, one time only, when the class is first loaded.
You may want to use "static block" to initialize your classes's static fields.
For example:
// start of static block
static {
//initialize your static fields
System.out.println("static block called ");
}
// end of static block
I'm trying to create a generic class that compares objects in an array list and returns the largest. My issue is that I'm not quite sure I understand completely how generics work.
Measurable:
import java.util.ArrayList;
/**
Describes any class whose objects can be measured.
*/
public abstract class Measurable<T>{
abstract double getMeasure();
public static <T extends Measurable<T>> T getLargest(ArrayList<T> objects){
T largest = objects.get(0);
for(int i = 0; i < objects.size(); i ++){
if(largest.getMeasure() == objects.get(i).getMeasure()){
largest = objects.get(i);
}
}
return largest;
}
}
Box:
import java.awt.Rectangle;
import java.util.ArrayList;
public class Box extends Measurable {
private Rectangle box;
private static ArrayList<Rectangle> rectangles;
public Box(){
box = new Rectangle();
rectangles = new ArrayList<Rectangle>();
}
public ArrayList<Rectangle> create(){
for(int i = 0; i < 10; i++){
box = new Rectangle((int) Math.random(), (int) Math.random());
rectangles.add(box);
}
return rectangles;
}
#Override
public double getMeasure() {
double area = 0;
for(int i = 0; i < rectangles.size(); i++){
area = rectangles.get(i).getWidth()*rectangles.get(i).getHeight();
}
return area;
}
public static void main(String[] args){
Box b = new Box();
b.getLargest(b.create());
}
}
I'm coming across an issue where it says "The method getLargest(ArrayList) in the type Measurable is not applicable for the arguments (ArrayList)" but shouldn't I be able to use any object for the getLargest class?
As you wrote it, getLargest expects the objects passed to it in the List to implement Measurable, but java.awt.Rectangle does not.
When you write
public static <T extends Measurable<T>> T getLargest(ArrayList<T> objects){
that declares a T that is different, but named the same, as the T in the Measurable class as a whole, which is likely to lead to total confusion.
If you actually replace T with Rectangle in your code, you can see that you're trying to call Rectangle.getMeasure(), which is a method that does not exist.
I am not really sure where generics come into play here. It seems like you want to make a bunch of shapes that are derived from a base class Measurable. You also want the abstract class to hold some code for working with Measurable subclasses. Basically you need to make a subclass that implements Measurable. I think what you want a Box class like the one below.
public class Box extends Measurable {
private double width;
private double height;
public Box(double width, double height){
this.width = width;
this.height = height;
}
public double getMeasure() {
double area = width*height;
return area;
}
}
Making an assignment and I've stumbled upon something I can't seem to fix nor properly seem to Google.
So I made a basic class like this with 3 attributes:
public class Planeet {
private int diameter;
private String naam;
private double relatieveMassa;
public Planeet(int diameter, String naam, double relatieveMassa) {
this.diameter = diameter;
this.naam = naam;
this.relatieveMassa = relatieveMassa;
}}
Now I made another class where I made an ArrayList from the class above and it contains methods to print out the list in different kinds:
public class Planeten {
private List<Planeet> planeten = new ArrayList<Planeet>();
public void sorteer(){
Collections.sort(??);
}}
Now my question is, how can I sort it on a specific attribute from my first class?
Thanks in advance and sorry if this is a silly question.
It's not a silly question, rather a newbish one. Please don't forget to include your getter(s) for the comparing fields (e.g. naam -> getNaam()).
public class PlaneetComparator implements Comparator<Planeet>
{
#Override
public int compare(final Planeet p1, final Planeet p2)
{
// Compare by names. Here, you can compare by any field you prefer.
return p1.getNaam().compareToIgnoreCase( p2.getNaam() );
}
}
After that:
Collections.sort(planeten, new PlaneetComparator());
Keep in mind this is just one way to do it. You could also use Comparable<T>, kudos to A4L.
Just implement Comparable to your class end override the compareTo method. In the method just compare the property u want to be compared when the sorting is applied.
Ex.
public class Planeet implements Comparable<Planeet>
private int diameter;
private String naam;
private double relatieveMassa;
public Planeet(int diameter, String naam, double relatieveMassa) {
this.diameter = diameter;
this.naam = naam;
this.relatieveMassa = relatieveMassa;
}
#Override
public int compareTo(Planeet arg0) {
//sorting on naam
return this.naam.compareTo(arg0.naam);
}
}
then in your other class just use
Collections.sort(planeten);
it will use the compareTo() method to sort them . If u want to make more sorting options, just make Comparators
Like what the title says, Can you make a public member of the superclass a protected member in a subclass? I had this question in my exam today, and I'm fairly new to programming. Can you explain how?
public class Animal {
int lifeExpectancy;
private int weight;
protected gender;
String name;
public String type;
String genders;
public Animal(int le, int w, char g, String n){
lifeExpectancy = le;
gender = g;
weight = w;
name = n;
}
this is the subclass
public class Pet extends Animal{
private String home;
private Boolean biten;
String message;
public Pet(int le, int w, char g, String n, String h, Boolean b) {
super(le, w, g, n);
lifeExpectancy = le;
gender = g;
weight = w;
name = n;
home = h;
biten = b;
}
No. Lets say you have A extends B, remember that this means you can always use an A as a B.
B b = new A();
So it can't be allowed for A to remove or restrict anything that B does, it can only extend it.
Overriden method:
must not have a more restrictive access modifier
may have a less restrictive access modifier.
level of restriction (from the most restrictive):
private
defualt
protected
public
Declaring member variable (tutorial):
you will shadow variable
In Java Member is Constructor, Field or Method.
class X1 {
public int x;
public X1() {
}
public void x () {
}
}
public class X extends X1 {
protected int x;
protected X() {
}
protected void x () {
}
}
compiler finds only one error in above
- Cannot reduce the visibility of the inherited method from X1
and there is no way it might allow it. As for constructor and field we do not change visibility of super class members we are just declaring the new ones
You can just inherit the properties. That's it.
Consider a case that If you use a subclass in place of superclass and you modified the accessor of that subclass, that breaks OOP rules.
You can not reduce the accessibility of an inherited item. And only instance methods are inherited. So you can re-define an instance or static property (not a method) in a child class with lower accessibility.
For static methods you still can not drop the accesibility though they are not inherited.