In OOP, class fields are characterized with several mutually exclusive options:
public vs private
final vs changeable (?)
static vs instance
Are there any other important characteristics of classes in Java or other common OOP languages, such as C++ and C#?
In programming, object oriented programming is a tool that has unleashed the real power of computing. OOP allows a programmer to define their own types and subsets of variables that they are able to use. Types like integers, doubles, strings, are all defined as a certain set of bits in the computers memory, so OOP gives a programmer the power to create their own types of mailable objects that can have different characteristics.
Public vs Private
These words reference the access that one has to variables and methods within a certain class. Public variables and methods are accessible anywhere meaning they can be called outside of the class that it exists in. Private methods and variables on the other hand, can only be called in the class where they exist.
Eg:
public class Vehicle{
private int milesPerGallon;
public int getMPG{
return this.milesPerGallon;
}
}
Vehicle car1 = new Vehicle();
In this example, the variable milesPerGallon is private while the accessor method (getMPG()) that returns this value is public. So, in order to get the miles per gallon for the car1 object, the programming could not call car1.milesPerGallon. They would instead have to call car1.getMPG() because that method is public.
The use of private variables may seem counterintuitive, but private class members are a way to manage complexity. If all members were public, then bugs and problems in code could be linked to any one of these public members. It is difficult to trace back problems to public members becasue they can be called anywhere. If something were to happen to a pri
A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.
-tdammers
Final vs Changeable
These two concepts refer to the malleability of variables within a class. If a member is final, this means that it cannot be changed later in the program. But without the final keyword, then the variables are free to change at any time. Say for example, you were writing a cash register class.
public class Register{
private final double valueOfPenny = .01;
private final double valueOfNickel = .05;
ect...
private int numberOfPennies;
private int numberOfNickels;
ect...
}
In the Register class you will obviously need to know the value of a penny, nickel, dime, ect. But these values are going to stay constant through out the program. So we can set the value of each coin to be a final variable so that it does not accidentally get changed on accident. On the other hand, the number of each coin inside of the register may change through out the program, so we cannot make these variables final.
Static vs Instance
A instance variable means that every object has its own copy of each instance variable. An easy way to remember this is to think that every instantiation of a variable has a copy of the instance variable in a class. By default, all variables of a class are instance variables.
Static variables on the other hand, belong only once to the entire class. No matter how many instantiations of the class have been made, the static variable still only belongs to the class as a whole.
Eg:
public class Vehicle{
private double milesPerGallon;
public static int numberOfVehicles;
}
Vehicle car1 = new Vehicle();
Vehicle car2 = new Vehicle();
Both car1 and car2 have a variable called milesPerGallon. This makes sense because different instances of the Vehicle class will have different values of MPG. But, the variable numberOfVehicles is static because it only acts as a counter for how many vehicles there are. Every vehicle does not need to know this information because it is pointless for car1 and car2 to know that there are 2 vehicles. Only the class must know the value of this variable.
Constructors
You asked if there was any additional information about OOP that would be important and I feel as if constructors are at the top of the list. The constructor is a method that gets called whenever a programmer makes a copy of a class. In other words, whenever the programmer makes a call and instantiates a class, the constructor is the first and only method that gets called. In Java, the constructor is required and the name of the constructor is the same name as the class. If you do not provide Java with a constructor, then it will generate a blank constructor for you. But the power of the constructor is very useful and should often be utilized. Let's go back to the Vehicle example. Let's say you want to make a vehicle that has a certain manufacturer and the year it was made. You can save these two pieces of information as private instance variables as we mentioned above. But every time a Vehicle object is created, you want these two variables to be set right away. (i.e. you want to construct the object).
public class Vehicle{
private makeOfVehicle;
private yearOfVehicle;
public Vehicle(String make, int year){ //constructor
this.makeOfVehicle = make;
this.yearOfVehicle = year;
}
}
Vehicle car1 = new Vehicle("Toyota",2005);
Vehicle car2 = new Vehicle("BMW",2002);
By using the constructor, you can set attributes of objects as they are created!
Please let me know if you have any questions concerning these concepts/code or any other OOP concepts
Related
PowerShell classes can contain static methods and properties:
class stack {
[string]
$name
[DateTime]
static $date = (GET-DATE)
stack($name) {
$this.name = $name
}
static [void] hello() {
Write-Host 'hello'
}
}
A couple use cases I've found so far for static methods:
organize my functions within a common context of a class.
I believe I have read somewhere that static methods are much more performant than functions. I've never verified it myself, though.
And for static properties:
They define variables that can be called from any scope, especially from within other classes without needing to pass the variable into the class as an argument.
I have the feeling that my reasons for using static methods / properties are pretty underdeveloped. Static properties in particular seem like more laborious alternatives to simple variables, although the omni-scope availability is very nice if you do run into that use case.
So my questions:
What use cases have you found for static methods/properties?
Does it ever make sense to set a static property without a default value?
Since PowerShell was given, I will give a .NET-centric answer.
Ultimately the details will vary from language to language, but static class instances are typically instantiated only once the first time a static member is called on it. This means you will have a single instance created for any code which needs to call it. Conversely, being able to call the constructor of a non-static class means you can create as many instances as times you can call the constructor. For classes with both static and non-static members, the static members are still only created a single time in memory for the static instance.
Create static methods if the method does not rely on instance data to get the job done. For example, a string class might include static utility methods that still require a source string to be passed in. Let's look at the signature of the built-in String.IsNullOrEmpty static method:
[string]::IsNullOrEmpty
# OverloadDefinitions
# -------------------
# static bool IsNullOrEmpty(string value)
IsNullOrEmpty makes sense to define as static because it does not make sense to have it operate on an instantiated string object instead. Think about what the method does. It checks for:
A null value; or
A value of [string]::Empty
It is a utility method in order check the conditions above against another string. If this were not a static method, we cannot check for a null string as the instance doesn't exist(you can't call a method on a null-valued expression). Even if we could have a null string and call the method, we would first need to create a string object to use it, which would allocate memory for IsNullOrEmpty for every single string object. None of this is efficient considering it's a utility method that can easily have a valid string passed into it.
The main benefit here is that you do not need to allocate memory for every static method for every string object created. As explained above, the static methods are instantiated only once for the static instance.
The same goes for properties, although oftentimes static properties are read only. One example might be a System Properties class, and the OS version may be a static string. Consider the static property I used above, [string]::Empty. If this were not a static property, we run into the same pitfalls as defining IsNullOrEmpty as a non-static member: it will get allocated more often than it needs to be, and we need to first create a non-null instance to use it. The latter occurs with static classes behind the scenes, so you are free to use static members without worrying about initialization or instantiation.
Note: Create a static class if all the members are planned to be static, as it does not make sense to create an instance when it would hold no stateful information. Static classes in .NET are classes that cannot be directly instantiated, except for a single static constructor.
To summarize, it's mostly about memory management. Static members are only created once during the lifetime of the program, while instance (non-static) members are created for each instance of the object created with new.
I missed a few CS classes, namely the ones going over topics such as polymorphism, inheritence, and abstract classes. I'm not asking you to do my homework but I have no idea where to even start to get further guidance, so giving me a skeleton or something would help me greatly, I'm so confused.
So the problem is to create an employee abstract class with two subclasses, permanentEmployee and TempEmployee.I must store information such as name,department,and salary in these subclasses and then order them according to how the user wants them ordered. I know I start out like this
public abstract class Employee
{
}
public class TempEmployee extends Employee
{
\\variables such as name, salary, etc, here?
}
public class PermEmployee extends Employee
{
\\here too?
}
but I have no idea how to store variables in there much less access them later for ordering and displaying,. Please guidance.
If all you're looking for is an example of class-level data members in Java, this should help:
public class SomeClass {
private int someInt;
public int getSomeInt() {
return this.someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
Regarding polymorphism, be aware that methods are polymorphic, but values are not. As you place values and methods (getters and setters) in your base class and derived classes, I encourage you to experiment with these concepts thoroughly. Try moving the entire value/getter/setter to the base class, try moving just the value but not the getter/setter, try putting the value in both and the getter/setter in both, etc. See how it behaves.
Make sure that any value/method/etc. that you put in your base class is applicable to all derived classes. If there's ever an exception to that rule, then you would need to move that member out of the base class and into only derived classes where it applies. Note that you can have a complex hierarchy of base classes to accommodate this if needed.
When it comes time to access these members for sorting/display/etc., consuming code would use the getters/setters. For example:
SomeClass myInstance = new SomeClass();
myInstance.setSomeInt(2);
System.out.println(myInstance.getSomeInt());
I am not sure which language you working with, but as it has "extends" I am sure you are not working with c# or CSharp, it can be Java. So I would recommend you to go for TutorialsPoint. This particular article has abstraction described here.
Just to make it easy for you, in Interface and abstraction we always create a structure or the base, it has all the common things defined or declared (Obviously interface has only methods and no variables can be declared inside it).
So as said, in above example, EmployeeId, EmployeeName, EmployeeAddress ...etc should be defined in the base class that is Abstract Base class Employee, But in TempEmployee you can have a criteria such as EmpTermPeriod, EmpContractRenewalDate, EmpExternalPayrollCompanyName (Have made names long and self descriptive) and PermEmployee to have fields like EmpJoiningDate, EmpConfirmationDate, EmpGraduityDate...etc.
I hope it helps.
I already know that you create an Interface within VB6.
Classes that implement an interface must implement ALL routines.
Is there a way to create something like an abstract class that may implement some routines.
Derived class must implement the abstract routines and may override the routines already implemented by the abstract class.
Please notice that we're talking about VB6 and not VB.NET or whatsoever.
Thank you
One work-around I use is to have an instance of the base class as a private member:
Implements Shape
Dim base as Shape
Dim radius as Single
Public Function Shape_Area() as Single
Shape_Area = pi*pi*radius
End Sub
Public Function Shape_PenColour() as Long
Shape_PenColour = base.PenColour() ' let the base do its thing
End Function
You could work up a hierarchy like that (for Square):
Implements Shape
Dim base as Rectangle
Public Function Shape_Area() as Single
Shape_Area = base.Area() ' which is Rectangle.Shape_Area which then calls the Shape.Area
End Sub
It does means that each class has to really know about the one it derives from. That may or may not be an issue for you. I have used it and it works well.
It does mean you have to do more work and each class explicitly
Visual Basic 6 does not support implementation inheritance, only interface inheritance. You can read more about it Here. There's a nice article here about interfaces and inheritance in VB6 that may lead you to a solution to your problem within VB6 capabilities.
A work-around (not a solution):
An interface, for instance, specifies routine A and B, implementing the second one.
A derived class has a private member being an instance of the interface.
The implementation of the routine B simply invokes that method on its private member.
Of course, we're dealing with 2 different objects but in some cases this may be good enough.
Implementation inheritance is over-rated and almost always ends up with complicated designs.
What you want to do achieve (provide base impl, reduce repeating code in derived classes, etc) can be done with composition and events
Consider interface IBase
Public Function GetArea() As Double
End Function
interface IDerived
Property Get Base() As IBase
End Property
Common implementation StdBaseImpl of IBase
Implements IBase
Event CustomizeArea(Value As Double)
Public Function GetArea() As Double
GetArea = 42
RaiseEvent CustomizeArea(GetArea)
End Function
Private Function IBase_GetArea() As Double
IBase_GetArea = GetArea
End Function
Then for derived classes you use composition and choose which base events to implement
Implements IDerived
Private WithEvents m_oBase As StdBaseImpl
Private Property Get IDerived_Base() As IBase
Set IDerived_Base = m_oBase
End Property
Private Sub m_oBase_CustomizeArea(Value As Double)
Value = Value + 10
End Sub
You can design bases with BeforeXxx + Cancel and AfterXxx events. You can sink multiple bases and coordinate them.
Static variables are variables allocated statically at compile time. My doubt is for what purpose some variables are declared statically? I didn't have used any static variable in my code till now. From the apple code http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html
in securityWrapper.m, there is a line
static SecKeyWrapper * __sharedKeyWrapper = nil;
what is the use of statically allocating __sharedKeyWrapper here?
I have seen the use of static key word in so many codes. So kindly explain the use and benefits when static keyword.
Thanks in advance.
That file global is a singleton, used for sharing an instance of a class.
The reason it's static in Objective-C is internal linkage. In practice, this means the variable can not be seen outside the file it is declared in. If another file declares a variable with the same name, they're two different variables.
Keep in mind that the way Objective-C instances work, the instance won't actually be allocated automatically. Rather, you have a pointer to the instance. The code will still have to do something like:
if ( !_sharedKeyWrapper ) {
_sharedKeyWrapper = [[SecKeyWraper alloc] initBlahBlah];
}
See links for more.
When you define a new class of objects, you can decide what instance
variables they should have. Every instance of the class will have its
own copy of all the variables you declare; each object controls its own
data.
However, you can't prescribe variables for the class object; there are
no "class variable" counterparts to instance variables. Only internal
data structures, initialized from the class definition, are provided for
the class. The class object also has no access to the instance variables
of any instances; it can't initialize, read, or alter them.
Therefore, for all the instances of a class to share data, an external
variable of some sort is required. Some classes declare static variables
and provide class methods to manage them. (Declaring a variable static
in the same file as the class definition limits its scope to just the
class-and to just the part of the class that's implemented in the file.
Unlike instance variables, static variables can't be inherited by
subclasses.)
Static variables help give the class object more functionality than just
that of a "factory" producing instances; it can approach being a
complete and versatile object in its own right. A class object can be
used to coordinate the instances it creates, dispense instances from
lists of objects already created, or manage other processes essential to
the application. In the case when you need only one object of a
particular class, you can put all the object's state into static
variables and use only class methods. This saves the step of allocating
and initializing an instance.
Also static variables are initialized once. You can use static variables in recursive calls. Simple Example Factorial.
What is the philosophy behind making the instance variables public by default in Scala. Shouldn't making them private by default made developers make less mistakes and encourage composition?
First, you should know that when you write:
class Person( val name: String, val age: Int ) {
...
}
name and age aren't instance variables but accessors methods (getters), which are public by default.
If you write instead:
class Person( name: String, age: Int ) {
...
}
name and age are only instance variables, which are private as you can expect.
The philosophy of Scala is to prefer immutable instance variables, then having public accessors methods is no more a problem.
Private encourages monoliths. As soon as it's easier to put unrelated functionality into a class just because it needs to read some variables that happen to be private, classes start to grow.
It's just a bad default and one of the big reasons for classes with more than 1000 lines in Java.
Scala defaults to immutable, which removes a massive class of errors that people often use private to restrict (but not remove, as the class' own methods can still mutate the variables) in Java.
with immutables which are preferred in many places, public isn't so much of an problem
you can replace a public val with getters and setters without changing the client code, therefore you don't need the extra layer of getters and setters just in case you need it. (Actually you do get that layer but you don't notice it most of the time.)
the java anti pattern of private field + public setters and getters doesn't encapsulate much anyway
(An additional view supplementing the other answers:)
One major driver behind Java's encapsulation of fields was the uniform access policy, i.e. you didn't have to know or care whether something was implemented simply as a field, or calculated by a method on the fly. The big upside of this being that the maintainer of the class in question could switch between the two as required, without needing other classes to be modified.
In Java, this required that everything was accessed via a method, in order to provide the syntactic flexibility to calculate a value if needed.
In Scala, methods and fields can be accessed via equivalent syntax - so if you have a simple property now, there's no loss in encapsulation to expose it directly, since you can choose to expose it as a no-arg method later without your callers needing to know anything about the change.