Java class confusion - java

The word 'class' is used very loosely in Java tutorials and study material. There are many many different meanings to this word. Can some body please enumerate and explain all meanings of this word. E.g.: 'class' means an object, 'class' is an file extension, 'class' is the first word used in declaring object, etc.

There are many many differnt meanings
to this word.
No. There is exactly one meaning:
A class is a blueprint for object instances
You define such a blueprint in your Java source code by using the 'class' keyword
The Compiler will turn your source code into byte code files - one file with the extension .class for each class in your source code
There are different places where the word "class" occur, but they are all related to the same basic meaning. Or are you also confused by the fact that "World of Warcraft" is a game you bought in a store, a shortcut on your desktop, and the name of a folder on your harddisk?

Class is an object-oriented term. A class is a description of a set of objects, the common behaviour they have and the state they have. Classes can inherit state and behaviour from superclasses. To put this another way:
Human is a class. Humans have state:
Eye colour;
Skin colour;
Type and colour of hair;
Height;
Weight;
and so on.
and behaviour:
Walk;
Run;
Swim;
Eat;
Drink;
etc.
Human has two subclasses in this example: Man and Woman. They have all the state and behaviour of Human but also some state and behaviour unique to each, like the obvious anatomical differences as state and behaviour as, for example, women can have babies.
An object is an instance of a slass. To put this another way: Megan Fox is an instance of the class Woman. Being a Woman, she is also an instance of the superclass Human.
As for Java, it generates one .class file for each class encountered when it compiles source code. Source files can contain multiple class files.

There is a keyword "class" use to define a class in Java. There is a "Class" class which is the parent class of all classes. And there is a ".class" which is a file extension.
You should be able to determine which is which from context.

class describes the blueprint or prototype from which objects are created.
object is an individual instance or unit of that class

A file can have several classes but just one public. The public one has to be the same name as the file for e.g public class Car - has to be Car.java.
You should name your classes starting with an uppercase and objects starting with an lowercase. A class contains a set of variables which tell you the state of a object from this class. A class contains a set of methods which tell you the behavior of the objects.
A class is like a describtion from one or more similar objects. A object is an instance of that class. You can have a Class Car with the variables speed, color, name. Then you can make for e.g. 2 objects peugeot and a porsche. Both can have diffrend speed, color and a name. You can make as many cars as you want by making a object from the class Car.

Related

Is this proper enum practice in Java?

I just started learning enums in Java and although the concept seems straightforward, its application isn't really intuitive to me. I see that I can put enums inside of classes although they are classes themselves.
I also saw online some people say you can only have one enum in a class, or that you shouldn't put all enums in a single class unless they are put private.
Thus, I'm a bit confused, would this piece of code be a proper writing of enum?
Thanks.
public class AirCraft
{
private AirType type;
private AirFixTime maintainTime;
private enum AirType
{
HELICOPTER,
AIRLINE,
BALLOON,
GLIDER;
}
private enum AirFixTime
{
WEEKLY,
MONTHLY,
YEARLY;
}
}
Technically, your code is properly written. Uses of enums depends of the functionality. Remember that the access modifiers are used to manage what you going to share or show to others. Right now your code is correct if the enums is going to be used just inside AirCraft.
Take a look at this
You have a choice of three places to put an enum definition.
Class of its own.
Nested within another class.
Locally, within a method (Java 16, now previewed in Java 15)
Context is key
You can place your enum definition anywhere that makes sense to you. It all depends on context.
If your enum is meant to be used in other code, on its own, put the enum in its own class.
If the enum really only makes sense when used within the context of a
particular class, then nest the enum.
If the enum objects are used only within the parent class’ own source code, make the enum definition private.
If the enum objects might be used by outside code working with objects of the parent class, make the nested class public. For example, a report building class might want to sort aircraft parts by their assigned AirCraft.Color enum object, to gather together all the safety-orange parts.
For example, consider the Month and DayOfWeek enum classes built into Java as part of the java.time classes. These enum definitions live in their own separate classes because they may be used in many different contexts, without the involvement of other java.time classes. These enums could be used on their own in workflow apps, sales reports, accounting apps, and more.
In contrast, imagine a UI framework tracking mouse events. There we might find a Event enum for mouse events, defining objects named HOVER, CLICKED, and DRAGGED. This enum would best be housed within the Mouse class as it only has meaning within the context of the outer mouse-handling class.
Another example, colors.
An enum listing all the standard colors named in Cascading Style Sheets (CSS) should be in its own class, as many kinds of code may use that.
An enum listing colors used in color-coding parts of your aircraft should be nested within the AirCraft class, its only sensible context.
Usages:
myWebPage.setBackground( CssColor.DARK_SLATE_GREY ) ; // This enum could be used on its own with many classes in different frameworks. So define enum in a separate class..
myAircraft.getEmergencyStopButton().setColor( AirCraft.Color.SAFETY_ORANGE ) ; // This enum is only ever used in contexts using its parent class, so nest the enum definition.
If nesting, think about your naming. I would likely name the enum Color rather than AircraftColor, because the nested notation AirCraft.Color.x makes clear the context. On the other hand, some folks like to use a static import to be able to use Color.x without the AirCraft. prefix (not my preference).
Local enums
New in Java 16 will be local enums (previewed in Java 15). That means enums defined within a method.
This new feature seems to be documented only as a mention within the new Records feature: JEP 384: Records (Second Preview).
private void demoLocalEnum ( )
{
enum Color { PURPLE , SAFETY_ORANGE }
System.out.println( Color.PURPLE ) ;
}
As we can see in this screenshot, the enum only exists within the method containing its declaration. A sibling method on the same class does not know of the enum’s existence. In this example, trying to use the enum within another method generates an error within the IDE’s code editor.
Use this where your enum makes sense only within one chunk of code. If your enum is only used within a single method, then declaring it as a nested class draws undue attention. Being tucked away inside that method is more tidy.

About class and object relationship [duplicate]

This question already has answers here:
The difference between Classes, Objects, and Instances
(16 answers)
Closed 4 years ago.
Can I say that class is a manual for building up an object?
I agreed that object is one of the instance of class.But if some properties that defined by classes may not make sense for particular object, for example,I have an object called "Duck" which use the class "Bird" for build, but Duck cannot fly,so if I use class "Bird" for build up an object "Duck".In the other words, the manual cannot provided the guideline for build up the object.
So,can i say that class is a manual for building up an object?As well as the manual should provided all the functions that the users need,in case there shouldn 't have any defects inside.
You are mixing two things at the same time:
On one hand you have to know that a class is just some kind of a template for an object instance, as it will show you what are the attributes and methods that any instance of that object can do. For example, you can think about the class "Car". Each car will have a different colour and a different plate number. That's a good sign for us to think that those two can be attributes of the class.
On the other hand, you have to know that sometimes classes are related between them and you have some tools to resolve your problems. That's when inheritance and interfaces come along in your example. As you can imagine, any duck is a bird, but not any birds are ducks. Therefore, you can establish a class inheritance between Bird (as a "father" class) and Duck (as a "child" class), because a lot of the behaviour between birds can be defined for all of them. In your specific example, you will define the "flying" methods in Bird subclasses.
Moreover, you can say that this example should have Bird as an abstract class, because Bird is a "concept" but it cannot exist by itself (you can also think in "polygon" and "triangle", polygon doesn't make sense by itself).

How to show instance of class within a class in UML?

If you want to show, for example, that a class Match contains an instance of class Game and class Set, then do you just simply have them in the attributes or do you have a line to the classes representing that when the instance of Match is created then that also creates an instance of Game and Set?
Here's what I mean in code:
public class Match {
private Set set = new Set();
private Game game = new Game();
}
This kind of relationship between classes is called association. Association is marked in UML with simple arrow:
We also have to types of association:
1. Composition - when our class contains reference to the other class and other class cannot exist without our class.
For example Human contains Hand, Leg, Heart, Car conatins Engine, Wheels. This type of association is understood as strong reference in garbage collection programming languages.
2. Aggregation - when our class contains reference to the other class and other clas can exist without our class, for example School contains Student.This type of association is understood as weak reference in garbage collection programming languages.
Composition is definetly the stronger one.
Hope it helps.
Both listing as attributes and showing as association (line pointing to another class) are valid and have exactly similar semantic.
Showing graphically rather than textually gives you opportunity to optionally present additional information: aggregation/composition, availability, ownership. Yet if none of this is present or important, the meaning is precisely the same and one can be replaced with another depending on what is more useful for you.

Can you name an abstract class Object?

Considering everything is object oriented etc, so names have to describe the object and what it is, I have an abstract class that sub classes inherit from. These are all objects on the screen (it's a game), i.e, player, and a weight (trapezoid weight). I have it currently named Character but it doesn't seem fitting as the weight is not a Character itself, it only inherits properties from Character.
Could I call this class "Object" without it breaking conventions? - could someone come up with a more appropriate name?
Technically, you could - but it's a very, very bad idea, so don't.
Longer explanation: The Object class already in Java is java.lang.Object - so there's no technical reason why you could create another Object class in another package, just as you could create another String class in another package. (Actually, technically speaking you could even create your own java.lang.Object, but I'm not even going to go there!)
However:
Could I call this class "Object" without it breaking conventions?
Without breaking convention? Not in the slightest. You should never duplicate such commonly used class names elsewhere, especially those in java.lang. It would be considered incredibly bad code design.
In terms of a better name, Actor or Sprite may be two good alternatives.
Java's Object class is part of the java.lang package which is automatically imported for every class file. If you name your class Object and forget to explicitly import it in other classes, you will have issues, thinking you're using com.custom.Object (your class), but actually using java.lang.Object, the JDK's.
Use a more descriptive name, ApplicationObject.
Yes you can. The class beside the name has the path that is package.
package org.stackoverflow
public class Object {
}
By default java.lang is prohibited package name so you can not do declare
package java.lang
public class Object {
}
The class names does not have to be unique in scope of whole world. Using the class path you are able to override the JVM definition of class.

UML diagram for program (Class diagrams)

My program has one public class followed by a constructor and 2 local classes (the inner classes have action events) called from a method. There is one additional static methods.
Public class
Constructor
local Classes
Methods
I am very confused to how the UML diagram would look for this. I have made one for a super class and subclasses before and it was straightforward enough, but i'm not sure how to include local classes and action events (like key listener).
Thank you for your help. I am new to java so go easy please.
Edit: I meant Class diagrams not all UML in general. Sorry.
A quick Google search yielded the following from http://www.sparxsystems.com/resources/uml2_tutorial/uml2_classdiagram.html:
Nestings
A nesting is connector that shows the source element is nested within the target element. The following diagram shows the definition of an inner class, although in EA it is more usual to show them by their position in the project view hierarchy.
(source: sparxsystems.com)
UML defines 14 different types of diagrams. In the following I will assume you refer to the most common one: the Class Diagram.
Local classes have no inheritance relationship to the class they are defined in. However, each of their instances contain a reference to an instance of the class where they were defined. When you write new LocalClass() (which is the most usual), the referenced "parent" object is this. When you write aDefiningClassInstance.new LocalClass(), the referenced "parent" object is aDefiningClassInstance.
That clarified, the relationship of what you call the "public class" with the local classes is one of composition. Cardinality depends on you particular case, but it's most probably one-to-one with each local class.
Modern versions of UML introduce syntax for inner classes (which are practically the same as local ones), but IMHO this is excesively related to specific programming languages and does not represent the high-level relationships that UML is usually used for.
Whatever method calls the event handlers, it should belong to a class directly or indirectly storing references to them. Here you have two additional UML aggregation relationships (also of probable cardinality of one-to-one) if the calling method belongs to a class different to the defining one.

Categories