Some Java concepts I need explaining

Status
Not open for further replies.
Abstract Methods

I understand what an abstract class is, a class that you don't want an instance created of. What is an abstract method used for?

Static Methods

I understand what a static variable is, i.e one that is shared by every instance of the class and not created separately for each instance. How does this relate to methods? Surely all methods are static and the same method is shared by every instance. What is the point of creating a copy of the same method for instance?

Interface

I'm pretty sure I understand Interfaces. Correct me if I'm wrong, an interface is a list of un-implementated (i.e declaration but no body) methods that the class that uses it MUST use. Correct? I understand putting unimplementated methods in an interface but whats the point having constants in there?

Final Keyword

Is the only reason for creating a final class for security, to prevent un-authorized sub-classing? Is it good practice to do anyway?

Packages

Why for example when I have a single .java file program and I add 'package myStuff;' to the top it comes up with a long error on runtime? Everytime I add the word package to the top of 1 or more .java files I get errors? What am I doing wrong?

Thanks alot

Dom
 
D

Deleted member 43669

Guest
Originally posted by MrWhite:
_Abstract Methods_

I understand what an abstract class is, a class that you don't want an instance created of. What is an abstract method used for?

Having an abstract method means you cannot implement it yet, and you are waiting for a subclass to implement it. Great example a teacher once gave us; a class for physical objects, that leaves as abstract weight() and volume() (because it depends on the shape of an object) but implements density (which calls those abstract methods).

_Static Methods_

I understand what a static variable is, i.e one that is shared by every instance of the class and not created separately for each instance. How does this relate to methods? Surely all methods are static and the same method is shared by every instance. What is the point of creating a copy of the same method for instance?

It's not a difference on the code generated, it's something of how you use the methods. You can use static methods without instantiating an object of the class; it might be senseless to have an utility method that does not apply to an object to need to be called with an object.

_Interface_

I'm pretty sure I understand Interfaces. Correct me if I'm wrong, an interface is a list of un-implementated (i.e declaration but no body) methods that the class that uses it MUST use. Correct? I understand putting unimplementated methods in an interface but whats the point having constants in there?

Mmm... never thought of that. Well, it could be useful like #define's; you know, you change the interface and all the implementing classes change... I have never used this

_Final Keyword_

Is the only reason for creating a final class for security, to prevent un-authorized sub-classing? Is it good practice to do anyway?

Well, it also has some relevance to optimizing, I think; and some stuff with inner classes needs things to be declared final; but I'm not sure of both.

_Packages_

Why for example when I have a single .java file program and I add 'package myStuff;' to the top it comes up with a long error on runtime? Everytime I add the word package to the top of 1 or more .java files I get errors? What am I doing wrong?

Errmmm... dunno!
 
Abstract Method:

An abstract method is similar in nature to the methods in an interface. By that I mean there is no definition for that method, but any child must implement that method or it must itself be declared abstract. So its a way of guaranteing that any instance of a subclass of that class will have an implementation for that method.

Static Method:

I know all methods use the same "code" to perform on each instance of an object, but I don't think that means they are static. A static method could be called without first instantiating an object of that class. One static method I use often is the parseInt() method on Integer. Its a utility to get an int from a String and I can use it without needing to instantiate an Integer which I don't want to use other than for the utility method.

Interfaces:

You are correct, atleast to my understanding in terms of unimplemented methods. I use interfaces to hold constants as well. I declare them as static final. So any class I want to have access to these constants that could be important across several classes just need to implement this interface and they all have the constants locally. So I don't need to refer to the constants in another class such as ConstantClass.constant1, I can just go contant1 in the class I'm in. It is also much much better than declaring them across all classes individually because that way if you needed to change one you would have to find all instances of that constant to change and with placing them in an interface you only need to change one.

Final:

I'm sorry but I can't help much there.

Packages:

Packages are a way of organizing code. So if you have a bunch of code belonging to a common idea or function you would put them all in a single package. In order to use packages you need to put something like this:

code:<HR>
Code:
package myorganization.mypackage;<P>public class MyClass {
.
.
.
}

Now to compile that with javac you must place that class in the directory myorganization/mypackage (slash direction depends on OS). Then the javac command would look like this from the location where the myorganization directory lies:

javac -classpath . myorganization.mypackage.MyClass.java

To run the class with java:

java -classpath . myorganization.mypackage.MyClass

If you are doing all that and still having problems with packages I'm not sure what is wrong. Maybe you can list what errors you are getting at runtime.

gen
 
Having an abstract method means you cannot implement it yet, and you are waiting for a subclass to implement it. Great example a teacher once gave us; a class for physical objects, that leaves as abstract weight() and volume() (because it depends on the shape of an object) but implements density (which calls those abstract methods).
What's the point in putting in an abstract method if you have to implement it in the sub-class? You have to type the full function still in the sub-class wont you?

It's not a difference on the code generated, it's something of how you use the methods. You can use static methods without instantiating an object of the class; it might be senseless to have an utility method that does not apply to an object to need to be called with an object.
But you can use ANY method without creating an object of it can't you? If I declared a method without the static keyword, I could still use it by ClassName.methodName() couldn't I?


Thanks alot much appreciated.
 
Originally posted by MrWhite:
What's the point in putting in an abstract method if you have to implement it in the sub-class? You have to type the full function still in the sub-class wont you?

But if it is an abstract method, you can use it when you know the object will be of the base class, but you are not sure what the subclass will be; this works because any subclass you can instantiate must have an implementation of the abstract method.

This is called polymorphism, and is one of the key concepts in OOP.

you can use ANY method without creating an object of it can't you? If I declared a method without the static keyword, I could still use it by _ClassName.methodName()_ couldn't I?

No. That will not work.
In a static method, you have no copy of the this pointer, and thus no access to local non-static methods and properties.
If you do not declare the method static, the compiler will not know this, and will add in a reference to this; this means that even if you don't use anything non-static, you still won't be able to call the method without having an instantiated object.
 
Charley is right.

As for the abstract classes I use them all the time. Here is my lame ass attempt at explaining the usefulness:

Say I have a collection of shapes (ie circles, squares, triangles, etc). I know they are all shapes, but I don't know the specific types on them. All of these shapes are a subclass of the abstract class Shape. Shape can have whatever non-abstract methods it wants such as the color or something. Now if I give it an abstract method of getArea(), all subclasses must implement getArea() for that paricular shape (square l^2, circle pi*r^2, etc). Now if I have a collection of shapes of different types and I want to know the total area for all shapes I can call getArea() on all of them and know that the function will be implemented. Its a way of guaranteeing that all things of a type will have a common set of operations.

Does that help?

gen
 
Thats a lot tougher. There are a few considerations.

1. I use interfaces for my constants as stated earlier.

2. If you aren't actually going to implement anything in the abstract class you might as well use an interface as it still provides the ability to do things like my shape example. If you are going to implement something common across all of the children then you best use an abstract class.

3. If you want to have a class inherit from more than one thing. You can only extend one class (abstract or not) so if you need more you have to use an interface as a class can implement as many interfaces as you want.

gen
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by MrWhite:
Not to sure of when to use an interface and when to use abstract methods, is 1 a newer idea than the other or are they both to be used concurrently?

For answers to your specific questions, you may want to purchase The Java Programming Language, Third Edition by Arnold, Gosling, and Holmes. You can also dowload The Java Language Specification, Second Edition from Sun.

Beware that some of the answers you get in this forum are not very authoritative :(

Your general problem is one that many of those that don't have a CS background (and, I dare say, some of those that do) struggle with: How do the concepts of subclassing, subtyping, and is-a relationships map to the Java mechanisms of implementation inheritance (classes) and specification inheritance (interfaces)?

Definitions (1):

1) Subclassing is an implementation mechanism that allows code to be shared without requiring "cutting and pasting"
2) Subtyping is a relationship that allows an instance of a subtype to be used wherever an instance of a supertype is allowed
3) Is-a is a conceptual specialization relationship that holds whenever one kind of object is a special kind of another

All three provide a sort of reuse. Subclassing allows implementors to borrow code from existing classes to be used to implement new classes. Subtyping tells clients which classes can be substituted for other classes. Specialization tells a designer what the relationship between concepts in the design is.

It is useful to think of these as three different (but related) ideas. Abadi and Cardelli (2) describe three possible relationships between them.

If you think of a "type" as a set of values (an oversimplification), then a "subtype" of a type is a subset of that set of values. The distinguishing characteristic of subtying is subsumption:

(Subsumption): if a has type A and A is a subtype of B, then a has type B

Then, we can attribute a property known as subclassing-is-subtyping to certain languages:

(Subclassing-is-Subtyping): the type of instances of class c' is a subtype of the type of instances of class c if and only if c' is a subclass of c

Another language design is to replace (Subclassing-is-Subtyping) with:

(Subclassing-implies-Subtyping): if c' is a subclass of c then the object type of c' is a subtype of the object type of c

Object type is a little tricky. You can think of it as the protocol of the object: the visible fields, their types, and the signatures of all the visible methods.

(Subclassing-implies-Subtyping) is nice, because it decouples implementation from interface.

Yet another language design would be to eliminate the requirement of (Subclassing-is-Subtyping) or (Subclassing-implies-Subtyping), giving Inheritance-is-not-Subtyping (3)

Java provides the two mechanisms of implementation inheritance (extending a class) and specification inheritance (extending an interface), as well as interface specification (requiring a class to implement an interface).

What the hell does it all mean? Well, in Java, if one class is a subclass of another, then it is a subtype (i.e. you can use the subclass wherever an object of the base class is called for). Those objects (potentially) share some code.

You can also get subtyping in Java without subclassing. You can have subtyping between unrelated (implementation-wise) classes that do not share any code at all (i.e. if class c' implements a subinterface of an interface of class c).

My flippant answer to your question is that I tend to use interface inheritance when I want subtyping and class inheritance when I want subclassing ;)

In answer to your other question, subclassing is at least as old as Simula-67 (late 1960's), and I believe that subtyping (a la logic) is much older.

(1) LALONDE, W.R. AND PUGH, J. 1991. Subclassing != subtyping != is-a. J. Object-Oriented Program. 3, 5 (Jan.), 57--62.

(2) ABADI, M. AND CARDELLI, L. A Theory of Objects. Springer-Varlag: New York, 1996.

(3) COOK, W. R., HILL, W.L. AND CANNING, P. S. 1990. Inheritance is not subtyping. In Proceedings of the Seventeenth Annual ACM Symposium on Principles of Programming Languages (San Francisco, California, Jan. 17--19), ACM Press, 125--135.

[This message was edited by newton_meter on January 07, 2002 at 19:15.]
 
Here's a quick difference between Abstract Classes and Interfaces (from a C# point ov view, but same concept exactly)

For one project we were working on, we needed an object called a PostableDocument. At the beginning of the project, there were 5 or 6 defined ones, all sharing most of their logic. However, all of them accessed different tables/columns in a database and had a different method to verify and post the document. Most of them used the same method to Synchronize the data (ensure the object and the database had the smae data), but some cases later *might* require some tweaks. We left the "Post" method abstract, and the Synchronize method virtual (defined but overridable in inherited classes). Any Postable document we created needed to define the columns it used and the Post method, but for the most part, we didn't have to do much.

In another project, I built a message-passing system so components could communicate. They would register themselves with a central object which did most of the message shuttling. For an object to be registered to recieve messages, it had to be a MessageReceiver object. Since the scope of objects using the Messenger was very broad, we created a simple MessageReceiver Interface, that required only one function, ReceiveMessage(Message msg). Any component that implemented MessageReceiver could receive a message - all other behavior was seperate and unrelated.

Hope the real-world examples help some people iron out the differences.
 

Meister

Seniorius Lurkius
6
Mr White:

"Not to sure of when to use an interface and when to use abstract methods, is 1 a newer idea than the other or are they both to be used concurrently?"

They are both to be used concurrently in large scale development. When developing small apps, you can get sloppy and use them almost interchangably. Especially if you have been dabbling in C++, which doesn't really have interfaces as far as I remember. It uses abstract and 'completely virtual' (?) classes to fudge it if you want to use good OO design.

OK, I'll do my best to give my explanation.
I use interfaces to define the interface to a set of classes (say shapes). I use this when a client (say something that draws the shapes) will use different implementations of this interface (like squares and rectangles), but does not need to know about the specific objects it is handling (it just calls 'draw()'). The client treats them all as shapes. This is done to preserve encapsulation: classes not knowing more than they need to. Any shape that implements the shape interface can be cast to a shape object and treated as a shape. Only 'static final' variables can be declared in an interface: non-changing, instansiated variables ... constants.
An abstract class (abstractShape) will be an implementation of the interface, for concrete classes to inherit from (square, rectangle). The abstract class is not instansiable: it is only inherited from by concrete classes. In the abstractClass I would define default implementations of all the methods in the interface. These can then all be inherited, and overriden where necessary. Variables can be defined as normal in an abstract class, not only constants. Watch out for encapsulation though: not everything should be public, protected variables are more common than public ones in code I write.

Organising your classes like this gives you physically 'small' concrete classes (square, rectangle), maintains encapsulation (client deals with shapes only) ... and should make changes across the class heirarchy easy to make (through abstractShape). Many abstract classes can implement a common interface. For example you could have abstract classes such as:
abstractShape - standard
abstractPolygon - lined figure I think
abstractEllipse - curving doo-hicky, beziers and weird draw functions
...
an so on. With concrete classes that implement the shape interface, but inherit from the abstract class most like the shape that they are.

Phew, hope that wasn't complete gibberish.


Errm, Generator:

"If you want to have a class inherit from more than one thing."

Java does not support multiple inheritance. A java class can implement more than one interface. Method implementations can have different results, with the same interface. This is polymorphism, not multiple inheritance.
Multiple inheritance causes major problems if two implementations of the same method are provided by different superclasses. Thus, its tircky to get your head around: and not supported.

Did newton_meter confuse the hell out of anyone else ?
As far as I'm concerned, two classes implementing the same interface are not inheriting from each other. The only inheritance I am aware of in java is when 'extends superclass' is used. You inherit 'functionality'. I think some confusion may be down to the fact that the post seems to be removed from the java language, and the terms I would use are pretty specific to the java language.

As you have defined the terms ... in java I think this is what happens:
Subclassing is inheritance. Polymorphism can be used to alter the result of existing method calls, and extra methods can be added.

Subtyping "may" occur due to inheritance, but also due to interface implementation. Does the fact that a subclass and a superclass will share the same interface really need to be spelled out in this manner ? - thus, grouping in iterfacing as some sort of warped concept of inheritance ?

Is-a ... I must say I am totally confused about WTF this is supposed to be. The whole point of inheritance is to allow additional functionality to be added on to a defined class. If we inherited and added, or subtracted no functionality what have we got ? - nothing. This seems to be spelling out this fact in a very long and drawn out fashion, and defining some new terminology that I can see no parallel to in the java language.

interface inheritance ???? try to 'extend' an interface in java and see what happens =)
Interfaces are 'implemented' ... that is why they are defined interfaces, I have never heard them referred to as being 'inherited' from.
People can get real confused sometimes, and other people sometimes make it worse. I am trying to clarify the issues here, I think =)

To really get to grips with what your doing, go black box on an aplication framework of your choice. Play around with it, develop an understanding of it. I gaurentee you'll come out the other side and not want to see a textbook discuss any of these ideas again: because they are difficult to define rigidly without a v ast understanding of OO programming techniques.

-= The Meister =-

-
who jumped in limousines with the chinamen of oklahoma
on the premise of midnight moonlight smalltown rai

[This message was edited by Meister on January 07, 2002 at 21:29.]
 

gumbo

Ars Tribunus Angusticlavius
6,107
Also, interfaces are like completely abstracted classes.
I couldn't really understand if this has been said, but anyway...

Think of an abstract class as an interface. It is a particular type of interface that can have some methods defined in it, but others can be left empty and overridden for each subclass. (I think you have this down).

An abstract class (like said above) is used when there is a common code that can be used. If the draw() method of Shape draws lines connecting points, then it can be common to all classes.

This is where interface fields come in. The array or whatever that holds the points to be drawn can be defined in the interface, so it is shared across all implementors. The abstract class can use its defined fields in the methods it defines, and sub classes can use them also (if they are public).

If Circle, Square, and Triangle were subclasses of Shape, then drawing them would be taken care of, as would be the allocation of the shape storage. Then the subclasses must implement such methods as Area(), Length(), and Calculate(). Each method creates a shape or its values unique to the subclass.

If Shape was an interface, then the shape storage may be defined, but each implementor would have a specific draw() method - creating possible code replication.

Simple answer - Abstract classes (and methods) allow you to specify part of the class, but leave others up to the correct class. An interface requires all implementors to provide all methods, whether they are qualified to provide them or not.

I think I just summarized the thread, but oh well. :p

gubmo
 
I completely agree with newton... I wouldnt' take anything here as definitive... especially me ;) I'm just trying to help as best I can while trying to limit my spreading of misinformation.

Meister: You are correct, java does not have multiple inheritance, and I did a piss poor job of stating that.

The whole interface/abstract class thing is abit confusing to me in terms of either explaining it or using it properly. I use both, wether or not for the right thing is debatable. I guess I should leave explanations up to other people there.

gen
 

Meister

Seniorius Lurkius
6
gen:

Don't worry about getting things wrong, thats the whole point of java =)
Its always good to have different views on things. Problems arise because java can be confusing anyway, slack usage of terminology can get you into trouble if you're not careful.

gumbo:

"This is where interface fields come in. The array or whatever that holds the points to be drawn can be defined in the interface, so it is shared across all implementors."

I disagree with this. Variables and data structures' usage cannot be defnied in interfaces like this. The only was you can get an array into an interface is if it is the argument of a method. Thus, specifying the interface to the object. This is part a design issue, part the fact that java will not allow you to define an interface with variables in it.

Using abstract classes when you really mean interfaces can be dangerous. What happens when you want to have an object that will implement two interfaces ? - this can be done if you have defined them as interfaces, but not if you have defined them as abstract classes (multiple inheritance again).

Juat out of interest, do most people heavily design their java developments here ?
UML class diagrams ?
State transition diagrams ?
I tend to. Merely for the fact that I learned from experience.Its much easier to spend a week thinking about design and a day coding than it is to spend two weeks on coding as I go and and indefinate amount of time debugging.

Interfaces have their place, abstract classes have their place. If you can get a good handle on how to use them well while you are a beginner, I think it is a good thing to do. Basically, get thinking OO. You might not know all the java in the world (heaven help he who does), but you can apply you OO knowledge to create better organised software. (you will also be able to use the OO design for C# and C++ s you want)

-= The Meister =-

-
who jumped in limousines with the chinamen of oklahoma
on the premise of midnight moonlight smalltown rain.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by Meister:
Did newton_meter confuse the hell out of anyone else ?

That was not my intention.

As far as I'm concerned, two classes implementing the same interface are not inheriting from each other.

I never said that. You are confused. My claim was that you can have subtyping without subclassing, in Java. I can prove by example:

code:<HR>
Code:
interface I1 {}<P>interface I2 extends I1 {}<P>class C1 implements I1 {}<P>class C2 implements I2 {}

Class C2 is a subtype of class C1, though not a subclass. They are subtypes without sharing a single bit of implementation code. Quite easily done.

The only inheritance I am aware of in java is when 'extends superclass' is used. You inherit 'functionality'.

As I mentioned in my previous post, Java has two different types of inheritance: implementation inheritance and specification inheritance. To whit:

code:<HR>
Code:
class Identifier extends ClassType ...<P>interface Identifier extends InterfaceType ...

See sections 8.1.3 and 9.1.3 of the Language Specification.

I think some confusion may be down to the fact that the post seems to be removed from the java language, and the terms I would use are pretty specific to the java language.

I was trying to relate three specific Java mechanisms to three wider conceptual OO ideas. If your model of how inheritance works is "just like Java", then you will be poorly served when you step out into the wider world.

As you have defined the terms ... in java I think this is what happens:
Subclassing is inheritance.

Sort of. Subclassing is Java's implementation inheritance. Exactly. By definition.

Polymorphism can be used to alter the result of existing method calls, and extra methods can be added.

Perhaps I'm confused. Or you are. You said pretty much the same thing about altering result types twice in your message. You're certainly guilty of using non-Java terminology to talk about Java concepts. :) The language spec doesn't even mention polymorphism at all. Overloaded methods are distinguished by their signature; Java method signatures do not include the result type. The language spec doesn't say what happens if you try to change the result type, but the Sun JDK compiler gives a compile time error. Likewise, it is a compile time error (per the language spec) to override or hide a method and change the result type.

Subtyping "may" occur due to inheritance, but also due to interface implementation. Does the fact that a subclass and a superclass will share the same interface really need to be spelled out in this manner ? - thus, grouping in iterfacing as some sort of warped concept of inheritance ?

I'm not sure what you mean. Subtyping always occurs due to inheritance in Java, either implementation (class) inheritance or specification (interface) inheritance. The whole point of the "subclassing is not subtyping" camp is that only specification inheritance and not implementation inheritance should introduce subtyping relationships. You can disagree with the "should" part and choose a language that does what you want, you can't disagree that Java does what it does.

Is-a ... I must say I am totally confused about WTF this is supposed to be. The whole point of inheritance is to allow additional functionality to be added on to a defined class. If we inherited and added, or subtracted no functionality what have we got ? - nothing. This seems to be spelling out this fact in a very long and drawn out fashion, and defining some new terminology that I can see no parallel to in the java language.

Perhaps you should heed your own advice:

I would advise a read through of the GOF patterns book, it might help you clear up what is going on in an OO PL.

I would advise reading Section 1 (the basic stuff), particularly the subsections "Class versus Interface Inheritance" and the discussion of is-a versus has-a in the subsection "Inheritance versus Composition".

interface inheritance ???? try to 'extend' an interface in java and see what happens =)

I have. Now maybe you should. Or, check the Java class libraries, which are rife with examples. Interface java.io_ObjectInput extends interface java.io.DataInput.

Interfaces are 'implemented' ... that is why they are defined interfaces, I have never heard them referred to as being 'inherited' from.

Sigh.

People can get real confused sometimes, and other people sometimes make it worse.

I can't disagree with that.

(kg*m*m)/(s*s)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by newton_meter:
Class _C2_ is a _subtype_ of class _C1_, though not a _subclass_. They are subtypes without sharing a single bit of implementation code. Quite easily done.

I was hoping someone else would point out my sloppiness so I wouldn't have to. What I intended to say was:

The object type of class C2 (namely, I2) is a subtype of the object type of class C1 (namely, I1), though C2 is not a subclass of C1.

Subtyping in Java without using subclassing.

(kg*m*m)/(s*s)
 
This thread has many exhaustive explanations of the technical differences between "extends" and "implements". However, I like to keep things conceptual. Here's my take:

"extends" should be used when there is an 'isa' relationship between two classes. Conceptually, the child class is a more specific type of the parent.

"implements" should be used to indicate that certain classes are 'capable' of particular abilities. The classes that implement a particular interface are often completely unrelated.

So the difference comes down to "isa" vs. "iscapableof". The latter is often useful for noting capabilities such as "copyable", "drawable", "mutable", "pasteable", etc.

Colin
 
Status
Not open for further replies.