Java: help understanding the use of interfaces as a data type? - interface

I am having trouble understanding with some of the code snippets about this part of the Java tutorial: http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}
and:
public interface Relatable {
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other
public int isLargerThan(Relatable other);
}
In the first example, why am I downcasting Object types into Relatable types? What happens if the first method doesn't include the first two statements?
Let's say I wrote a Rectangle class that implements the Relatable interface and has the "findLargest" method. If I know that I'm comparing two Rectangle objects, why not just make the first method downcast the objects into Rectangles instead?

You cast the Objects into Relatable types because otherwise you cannot use the methods declared in the Relatable interface. Since Object does not have the isLargerThan method, you would get a compiler error without casting. Honestly, in my opinion the findLargest method as shown here was not very well designed; a better illustration of the purpose of Interfaces would be to ask for Relatable objects as the parameters like so:
public Object findLargest(Relatable object1, Relatable object2) {
//implementation not shown to save space
}
This way, the user must pass Relatable objects, but they can pass any object whose class implements Relatable (such as Rectangle)
"If I know that I'm comparing two Rectangle objects..."True, if you know that you are comparing two Rectangle objects, there is little use for an interface, but the purpose of interfaces is to allow you to create a generic "type" of object that can be used to define common features of several different classes.For example, what if you also had a Circle class and a Square class (both of which implemented Relatable)? In this case, you do not necessarily know the exact type of object you have, but you would know that it is Relatable, so it would be best to cast to type Relatable and use the isLargerThan method in a case like this.

Interfaces define a set of methods which every class which the interface implements has to implement. The downcast is necessary to get access to these methods.
You don't know if you are comparing rectangles with this interface. You could get any Relatble passed. This is one of the cases generics come in handy.

1.In the first example, why am I down casting Object types into Relatable types? What happens if the first method doesn't include the first two statements?
Answer
Every object has some basic functionality and you want a specific object write now. You are down casting your object into a "Relatable" so you can use the "isLargerThan" method(an object wont have it since it has only basic common stuff).
If you didn't down cast, you would not pass compilation.
2.Let's say I wrote a Rectangle class that implements the Relatable interface and has the "findLargest" method. If I know that I'm comparing two Rectangle objects, why not just make the first method downcast the objects into Rectangles instead?
Answer
Since you want to create something generic.
Lets say you have a Student and a Driver. Both of them are People. You can create an interface called IPeople and make both the Student and the driver implement it.
IPeople will have a method called "getAge()" that each of them will implement.
IPeople will have all the functionality that you need for "People". That's how you create cross object functionality under the "same hat".

Related

Is IEnumerable<object> the proper container for generic data sets?

Using Entity Framework, is IEnumerable the correct container to use to send back a generic data set? I.e. when I do not want to send back a list of the object, but just a generic a result set.
public IEnumerable<object> SelectPlayerFirstAndLastNameList()
{
return (from p in rlpEntities.Players select new { p.PlayerFirstName, p.PlayerLastName });
}
Thanks.
Here is the reference article, which talks about IList(inherits ICollection( and IEnumerable(Base Generic Interface for IQueryable,ICollection,List).
Here are the links which states generics & it's differences & it's usages,
Difference among IEnumerable , IQueryable, ICollection,IList, List
IEnumerable vs. ICollection vs. IQueryable vs. IList
Looking at your linq, it's about specific object & can be extended further in future. IQueryable is right fit for such scenario, as it gives client to iterate/add/remove items.
Check this link out Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?.
It really depends on your scenario, but IEnumerable<> would be used when you need to iterate, and List<> when you need to iterate and modify or sort the data.
IEnunerable<> - http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
List<> - http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
You can also use generics, to pass on whatever types you are querying against, like for instance
public IEnumerable<T> SelectPlayerFirstAndLastNameList<T>()
{
return (IEnumerable<T>)(from p in rlpEntities.Players);
}
So you can pass either object, or a known defined type. To call this you would do
var x = SelectPlayerFirstAndLastNameList<YourClassHere>();
I think what you have is correct but decide for yourself whether you should use it.
From MSDN: Anonymous Types in the Remarks section:
Anonymous types are class types that derive directly from object, and
that cannot be cast to any type except object.
and
To pass an anonymous type, or a collection that contains anonymous
types, as an argument to a method, you can declare the parameter as
type object. However, doing this defeats the purpose of strong typing.
If you must store query results or pass them outside the method
boundary, consider using an ordinary named struct or class instead of
an anonymous type.

Object as data attribute of class in Class diagram UML

Is the following format wrong if I add a pointer to an object of a class, as data attribute of class in Class diagram in UML?
could not find anything about using objects in class diagram, is
underlining the object correct within the class attributes?
I think you may be mis-understanding classes, objects and attributes. Apologies if it's me doing the mis-understanding. So. Here's the short answer:
it's absolutely fine and normal for the type of an attribute to be a Class. In other words, you're not restricted to using primitive types like int, long, char etc.
The consequence is, as you say, that the values of those attributes at run time will themselves be objects. Specifically, instances of the classes Ability, Move and See.
More specifically, each instance of Agent (i.e. each Agent object) will hold references - or more precisely pointers - to 3 other objects: one instance each of Ability, Move and See.
So, assuming that's right, what you have is correct - except for the underlining.
Underlining an attribute or operation says it sits at the class level - not the instance level. It's the equivalent of static in java. Think of declaring constants in class scope, or constructors.
If I understand your model that's not what you want. You want each instance of Agent to hold (a pointer to) its own instances of Ability, Move and See. You don't want all the Agent objects to share the same 3 instances. Assuming so, you don't need the underline.
Hope I understood and that helps.

What is exactly the point of auto-generating getters/setters for object fields in Scala?

As we know, Scala generates getters and setters automatically for any public field and make the actual field variable private. Why is it better than just making the field public ?
For one this allows swapping a public var/val with a (couple of) def(s) and still maintain binary compatibility. Secondly it allows overriding a var/val in derived classes.
First, keeping the field public allows a client to read and write the field. Since it's beneficial to have immutable objects, I'd recommend to make the field read only (which you can achieve in Scala by declaring it as "val" rather than "var").
Now back to your actual question. Scala allows you to define your own setters and getters if you need more than the trivial versions. This is useful to maintain invariants. For setters you might want to check the value the field is set to. If you keep the field itself public, you have no chance to do so.
This is also useful for fields declared as "val". Assume you have a field of type Array[X] to represent the internal state of your class. A client could now get a reference to this array and modify it--again you have no chance to ensure the invariant is maintained. But since you can define your own getter you can return a copy of the actual array.
The same argument applies when you make a field of a reference type "final public" in Java--clients can't reset the reference but still modify the object the reference points to.
On a related note: accessing a field via getters in Scala looks like accessing the field directly. The nice thing about this is that it allows to make accessing a field and calling a method without parameters on the object look like the same thing. So if you decide you don't want to store a value in a field anymore but calculate it on the fly, the client does not have to care because it looks like the same thing to him--this is known as the Uniform Access Principle
In short: the Uniform Access Principle.
You can use a val to implement an abstract method from a superclass. Imagine the following definition from some imaginary graphics package:
abstract class circle {
def bounds: Rectangle
def centre: Point
def radius: Double
}
There are two possible subclasses, one where the circle is defined in terms of a bounding box, and one where it's defined in terms of the centre and radius. Thanks to the UAP, details of the implementation can be completely abstracted away, and easily changed.
There's also a third possibility: lazy vals. These would be very useful to avoid recalculating the bounds of our circle again and again, but it's hard to imagine how lazy vals could be implemented without the uniform access principle.

What is the base of all interfaces in .net, just like the base for all classes is the object

I would like to pass an interface to a method signature which takes Object as its parameter, so I wonder about this question
public Stream GetViewStream(string viewName, object model, ControllerContext context)
instead of object I shall like to pass an interface Imodel, without modifying the signature. Is there a base class for interfaces?
Also in the new mvc2 is there a way to avoid controllercontext altogether?
I'd only answer the first question - Why there's no common base interface for all interfaces ?
First of all, there's no common pre-defined base interface for all interfaces, unlike the System.Object case. Explaining this can get very interesting.
Let us assume, you could have a common interface for all interfaces in the system. That means, all interfaces will need to force their implementations to provide implementation-details for that common base interface. In general, interface are used to give specific special behaviors to their concrete implementation classes. Obviously you only want to define an interface when you only know what to do and don't know HOW to do that. So, if you let there be a common base interface for all interface and force the implementations to expect them to provide details of how to do it - why would you want to do it ? What common task each class should do that varies from one another ?
Lets look at the other side of the coin, why we have System.object as base class of any .Net type - It is simple it gives you some methods that have COMMON implementation for any .Net type and for those methods that it might vary from type-to-type they have made it virtual ex: .ToString()
There's possibly no assumption of any
system-wide interface method which is
virtual/abstract to all its
implementations.
One common practice of using Interface is say, defining a particular behavior to any type. Like I'd have an interface IFlyable which will give Fly() to all types that implement IFlyable. This way I can play with any Flyable object regardless of its inheritance hierarchy coming into picture. I can write a method like this..
public void FlyTheObject(IFlyable flyingObject)
{
flyginObject.Fly();
}
It does not demand anything from the object but the implementation of the Fly() method.
EDIT
Additionally, All interfaces will resolve to Object because interfaces cannot be instantiated. The object is always of a concrete class that can be instantiated. This class may or may not implement your interface but as we know, any .Net type is ultimately based to System.Object, so you will be able to take the instance into an object type regardless of the fact if it implements a particular interface or not.
No, there is no base class for interfaces. Nor there is base interface for interfaces.
As for your second question (and partly first one) - what are actually you trying to do?
There is no base class for interfaces, but you can pass any interface variable e.g:
private IEnumerable<int> myInterfaceVariable = new List<int>();
to your method because by definition anything that is stored in that variable must be an instance of a class that inherits from the interface - therefore it must be an object.
The following compiles fine:
public class InterfaceAsObject
{
private IEnumerable<int> myInterfaceVariable = new List<int>();
private void CallDoSomething()
{
DoSomething(myInterfaceVariable);
}
private void DoSomething(object input)
{
}
}
Re 1, there is no base interface, but if I understand you correctly, you can achieve what I think you want by just passing your object that implements IModel via the model parameter and cast (and check!) the parameter to IModel. I use 'as' and check for null.
If you don't need total flexibility, a better way of doing this is to define the interface that the model parameter must support. If the specific objects support derived interfaces (e.g. IDerivedModel : IModel) this will work too.
Look up a text-book on polymorphism.

How do I use classes?

I'm fairly new to programming, and there's one thing I'm confused by. What is a class, and how do I use one? I understand a little bit, but I can't seem to find a full answer.
By the way, if this is language-specific, then I'm programming in PHP.
Edit: There's something else I forgot to say. Specifically, I meant to ask how defining functions are used in classes. I've seen examples of PHP code where functions are defined inside classes, but I can't really understand why.
To be as succinct as possible: a class describes a collection of data that can perform actions on itself.
For example, you might have a class that represents an image. An object of this class would contain all of the data necessary to describe the image, and then would also contain methods like rotate, resize, crop, etc. It would also have methods that you could use to ask the object about its own properties, like getColorPalette, or getWidth. This as opposed to being able to directly access the color pallette or width in a raw (non-object) data collection - by having data access go through class methods, the object can enforce constraints that maintain consistency (e.g. you shouldn't be able to change the width variable without actually changing the image data to be that width).
This is how object-oriented programming differs from procedural programming. In procedural programming, you have data and you have functions. The functions act on data, but there's no "ownership" of the data, and no fundamental connection between the data and the functions which make use of it.
In object-oriented programming, you have objects which are data in combination with actions. Each type of data has a defined set of actions that it can perform on itself, and a defined set of properties that it allows functions and other objects to read and write in a defined, constraint-respecting manner.
The point is to decouple parts of the program from each other. With an Image class, you can be assured that all of the code that manipulates the image data is within the Image class's methods. You can be sure that no other code is going to be mucking about with the internals of your images in unexpected ways. On the other hand, code outside your image class can know that there is a defined way to manipulate images (resize, crop, rotate methods, etc), and not have to worry about exactly how the image data is stored, or how the image functions are implemented.
Edit: And one more thing that is sometimes hard to grasp is the relationship between the terms "class" and "object". A "class" is a description of how to create a particular type of "object". An Image class would describe what variables are necessary to store image data, and give the implementation code for all of the Image methods. An Image object, called an "instance" of an image class, is a particular use of that description to store some actual data. For example, if you have five images to represent, you would have five different image "objects", all of the same Image "class".
Classes is a term used in the object oriented programming (OOP) paradigm. They provide abstraction, modularity and much more to your code. OOP is not language specific, other examples of languages supporting it are C++ and Java.
I suggest youtube to get an understanding of the basics. For instance this video and other related lectures.
Since you are using PHP I'll use it in my code examples but most everything should apply.
OOP treats everything as an object, which is a collection of methods (functions) and variables. In most languages objects are represented in code as classes.
Take the following code:
class person
{
$gender = null;
$weight = null;
$height = null;
$age = null;
$firstName = null;
$lastName = null;
function __CONSTRUCT($firstName, $lastName)
{
//__CONSTRUCT is a special method that is called when the class is initialized
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
This is a valid (if not perfect) class when you use this code you'll first have to initailize an instance of the class which is like making of copy of it in a variable:
$steve = new person('Steve', 'Jobs');
Then when you want to change some property (not technicaly the correct word as there are no properties in PHP but just bear with me in this case I mean variable). We can access them like so:
$steve->age = 54;
Note: this assumes you are a little familiar with programming, which I guess you are.
A class is like a blueprint. Let's suppose you're making a game with houses in it. You'd have a "House" class. This class describes the house and says what can it do and what can be done to it. You can have attributes, like height, width, number of rooms, city where it is located, etc. You can also have "methods" (fancy name for functions inside a class). For example, you can have a "Clean()" method, which would tell all the people inside the house to clean it.
Now suppose someone is playing your game and clicks the "make new house" button. You would then create a new object from that class. In PHP, you'd write "$house = new House;", and now $house has all the attributes and methods of a class.
You can make as many houses as you want, and they will all have the same properties, which you can then change. For example, if the people living in a house decide to add one more room, you could write "$house->numberOfRooms++;". If the default number of rooms for a house was 4, this house would have 5 rooms, and all the others would have 4. As you can see, the attributes are independent from one instance to another.
This is the basics; there is a lot more stuff about classes, like inheritance, access modifiers, etc.
Now, you may ask yourself why is this useful. Well, the point of Object Oriented Programming (OOP) is to think of all the things in the program as independent objects, trying to design them so they can be used regardless of context. For example, your house may be a standalone variable, may be inside an array of houses. If you have a "Person" class with a "residence" attribute, then your house may be that attribute.
This is the theory behind classes and objects. I suggest you look around for examples of code. If you want, you can look at the classes I made for a Pong game I programmed. It's written in Python and may use some stuff you don't understand, but you will get the basic idea. The classes are here.
A class is essentially an abstraction.
You have built-in datatypes such as "int" or "string" or "float", each of which have certain behavior, and operations that are possible.
For example, you can take the square root of a float, but not of a string. You can concatenate two strings, or you can add two integers. Each of these data types represent a general concept (integers, text or numbers with a fixed number of significant digits, which may or may not be fractional)
A class is simply a user-defined datatype that can represent some other concept, including the operations that are legal on it.
For example, we could define a "password" class which implements the behavior expected of a password. That is, we should be able to take a text string and create a password from it. (If I type 'secret02', that is a legal password). It should probably perform some verification on this input string, making sure that it is at least N characters long, and perhaps that it is not a dictionary word. And it should not allow us to read the password. (A password is usually represented as ****** on the screen). Instead, it should simply allow us to compare the password to other passwords, to see if it is identical.
If the password I just typed is the same as the one I originally signed up with, I should be allowed to log in. But what the password actually is, is not something the application I'm logging in to should know. So our password class should define a comparison function, but not a "display" function.
A class basically holds some data, and defines which operations are legal on that data. It creates an abstraction.
In the password example, the data is obviously just a text string internally, but the class allows only a few operations on this data. It prevents us from using the password as a string, and instead only allows the specific operations that would make sense for a password.
In most languages, the members of a class can be either private or public. Anything that is private can only be accessed by other members of the class. That is how we would implement the string stored inside the password class. It is private, so it is still visible to the operations we define in the class, but code outside the class can not just access the string inside a password. They can only access the public members of the class.
A class is a form of structure you could think of, such as int, string and so forth that an instance can be made from using object oriented programming language. Like a template or blueprint the class takes on the structure. You write this structure with every association to the class. Something from a class would be used as an object instance in the Main() method where all the sysync programming steps take place.
This is why you see people write code like Car car = new Car();to draw out a new object from a class. I personally do not like this type of code, its very bad and circular and does not explain which part is the class syntax (arrangement). Too bad many programmers use this syntax and it is difficult for beginners to understand what they are perceiving.
Think of this as,
CarClass theCar = new CarClass(); //
The class essentially takes on the infinitely many forms. You can write properties that describe the CarClass and every car generated will have these. To get them from the property that "gets" what (reads) and "sets" what (writes) data, you simply use the dot operator on the object instance generates in the Main() and state the descriptive property to the actual noun. The class is the noumenon (a word for something like math and numbers, you cannot perceive it to the senses but its a thought like the #1). Instead of writing each item as a variable the class enables us to write a definition of the object to use.
With the ability to write infinitely many things there is great responsibility! Like "Hello World!" how this little first statement says much about our audience as programmers.
So
CarClass theCar = new CarClass(); //In a way this says this word "car" will be a car
theCar.Color = red; //Given the instance of a car we can add that color detail.
Now these are only implementations of the CarClass, not how to build one.
You must be wondering what are some other terms, a field, constructor, and class level methods and why we use them and indexing.
A field is another modifier on a property. These tend to be written on a private class level so nothing from the outside affects it and tends to be focused on the property itself for functionality. It is in another region where you declare it usually with an underscore in front of it. The field will add constraints necessary to maintain data integrity meaning that you will prevent people from writing values that make no sense in the context. (Like real like measurements in the negative... that is just not real.)
The Constructor
The easiest way to describe a constructor is to make claims to some default values on the object properties where the constructor scope is laid. In example a car has a color, a max speed, a model and a company. But what should these values be and should some be used in millions of copies from the CarClass or just a few? The constructor enables one to do this, to generate copies by establishing a basic quality. These values are the defaults assigned to a property in a constructor block. To design a constructor block type ctor[tab][tab]. Inside this simply refer to those properties you write above and place an assigned value on it.
Color = “Red”;
If you go to the main() and now use the car.Color property in any writing output component such as a the console window or textbox you should see the word “Red”. The details are thus implicit and hidden. Instead of offering every word from a book you simply refer to the book then the computer gets the remaining information. This makes code scripts compact and easy to use.
The Class level method should explain how to do some process over and over. Typically a string or some writing you can format some written information for a class and format it with placeholders that are in the writing to display that are represented with your class properties. It makes sense when you make an object instance then need to use the object to display the details in a .ToString() form. The class object instance in a sense can also contain information like a book or box. When we write .ToString() with a ToString override method at class level it will print your custom ToString method and how it should explain the code. You can also write a property .ToString() and read it. This below being a string should read fine as it is...
Console.Writeline(theCar.Color);
Once you get many objects, one at a time you can put them in a list that allows you to add or remove them. Just wait...
Here's a good page about Classes and Objects:
http://ficl.sourceforge.net/oo_in_c.html
This is a resource which I would kindly recommend
http://www.cplusplus.com/doc/tutorial/
not sure why, but starting with C++ to apply OOP might be natural prior of any other language, the above link helped me a lot when I started at least.
Classes are a way programmers mark their territory on code.
They are supposedly necessary for writing big projects.
Linus and his team must have missed that memo developing the linux kernel.
However, they can be good for organization and categorizing code I guess.
It makes it easier to navigate code in an ide such as visual studio with the object browsers.
Here are some usage demonstrations of classes in 31 languages on rosettacode
First of all back to the definitions:
Class definition:
Abstract definition of something, an user-type, a blueprint;
Has States / Fields / Properties (what an object knows) and Methods / Behaviors / Member Functions (what an object does);
Defines objects behavior and default values;
Object definition:
Instance of a Class, Repository of data;
Has a unique identity: the property of an object that distinguishes it from other objects;
Has its own states: describes the data stored in the object;
Exhibits some well defined behavior: follows the class’s description;
Instantiation:
Is the way of instantiate a class to create an object;
Leaves the object in a valid state;
Performed by a constructor;
To use a class you must instantiate the class though a contructor. In PHP a straight-forward example could be:
<?php
class SampleClass {
function __construct() {
print "In SampleClass constructor\n";
}
}
// In SampleClass constructor
$obj = new SampleClass ();
?>