new C# class

Advertisements

Hello everybody,

Michael here, and today’s post will cover classes in C#.

What is a C# class? Better yet, what is a programming class in general?

If you’ve learned other programming languages, you’ll certainly have encountered this concept. However, in case you need a refresher, C#, like Java and Python (and possibly many other languages) is what’s known as an object-oriented programming language. Just like with Java and Python, everything comes in classes and objects. All those classes and objects come with their own methods and attributes.

new C# class

Now, how do we construct a C# class? Take a look at this example below:

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);

    }
}

11

In this simple Cat class, we have three attributes-color, age, and gender. We also created an object of the Cat class in the Main() (yes C# capitalizes the word Main) method called orangeCat and accessed its age attribute with the following code-orangeCat.age-which returns the value of 11.

  • To access any attribute of a C# object, remember the following syntax: objectname.attributename.

Easy enough right? Now let’s see some new C# class tricks!

new C# class (no default values)

Now, how do we create a C# class with no default values? Let’s take a look:

class NewCat
{
    string color;
    int age;
    string gender;

    public NewCat(string catColor, int catAge, string catGender)
    {
        color = catColor;
        age = catAge;
        gender = catGender;
    }

    static void Main(string[] args)
    {
        NewCat brownCat = new NewCat("brown", 11, "female");
        Console.WriteLine("This is a " + brownCat.color + " cat who is " + brownCat.age + " years old and is a " + brownCat.gender);

    }
}

This is a brown cat who is 11 years old and is a female

In this example, I didn’t declare default values for color, age, and gender. Instead, I used a special method called a constructor to allow any object of the Cat class to be initialized with any possible value for each attribute. The constructor must have the same name as the class (Cat in this case) and can contain as many parameters as you want (3 parameters in my case for color, age, and gender).

Notice how I still declared the color, age, and gender variables before the constructor even though I use these same three variables inside the constructor. Why might that be? The first time I mention color, age and gender, all I did was declare that these variables will be a part of this Cat class. However, when I mentioned them again in the constructor, I actually initialize them to whatever the values of catColor, catAge and catGender are set to in the parameters.

  • Remember that before you initialize a variable with a constructor, you must first declare it!
  • Even though I didn’t give any default values for each variable, I can still access each variable in the same manner I did in the previous example (e.g. objectname.attributename).
  • Yes, since I stored each example as a separate script in the same directory, I used the name NewCat for this class. Keep in mind that if you’re going to create multiple classes in the same directory, you must use different names for each class.

Here are the links to both of today’s scripts in my GitHub:

Thanks for reading,

Michael

Python Lesson 14: Inheritance

Advertisements

Hello everybody,

Michael here, and today’s lesson will be on inheritance in Python. Inheritance in Python is the same concept as inheritance in Java-a child class inherits all of the methods and attributes from another class called the parent class. However, inheritance in Python is executed differently than inheritance in Java, and this post will describe how inheritance in Python works.

To demonstrate inheritance, let’s first create a parent class:

In the parent class Team, I have two functions-__init__ and printInfo. The __init__ function accesses the class’s two main parameters-teamName and Location. The printInfo function prints the String The {teamName} are located in {location}.

  • The f in the print line denote that the String I’m trying to print is an f-string literal, which is a neat way to format Strings and concatenate values.
  • When inputting the parameter names into the f-string literal, remember to use the keyword self (or whatever word you used in place of self) in front of the parameter name just as I did for self.teamName and self.location.

OK, so now let’s create an object of the Team class and execute the printInfo method:

Now let’s create a class called BasketballTeam, which will serve as a child class of the Team class:

Inheritance with Python classes is conceptually the same as inheritance with Java classes but inheritance with Python classes has much different syntax.

To create a child class in Python, use this general syntax: class ChildClass (ParentClass).

You’ll also notice that I used the pass keyword as the body of the BasketballTeam class. However, when it comes to child classes, pass doesn’t mean the class is empty. Instead, pass means that all methods and attributes from the parent class are inherited, but you don’t want to add any new methods or attributes to the child class that aren’t in the parent class.

Now let’s create an object of the BasketballTeam class and call the printInfo function:

Looks like the inheritance worked like a charm!

Now, what if we wanted to use the __init__ function for our child class instead of the pass keyword? Let’s see how we would execute that:

In this example, the child class’s __init__ function overrides the parent class’s __init__ function. However, the printInfo function is unaffected by this change.

To keep the parent class’s __init__ function, be sure to call the parent class’s __init__ function in the child class’s __init__ function:

  • As you can see, the printInfo function works the same regardless of whether I use the parent class’s __init__ function or the child class’s __init__ function.

Now, what if you wanted the child class to inherit all of the methods and attributes from the parent class? To do this, use the keyword super (with parentheses):

When using the super() keyword in a child class, keep these three things in mind:

  • Place the super() keyword in the body of the child class’s __init__ function.
  • After using the super() keyword, remember to call the __init__ function. Also remember to use all of the parameters of the child class’s __init__ function except for self (or whatever you decided to call the self parameter).
  • Super() inherits all of the methods and attributes from the parent class, so there’s no need to mention the parent class (Team in this case)

Now, what if we wanted to add an attribute that is exclusive to the child class? Let’s see how we can accomplish that:

To add an attribute that is exclusive to a child class, use this syntax: self.(name of attribute) = value of attribute. Also remember to place any new attributes in the body of the child class’s __init__ function (not the super().__init__ function call).

Now I need to make another change to my code? What could that be?:

I needed to include my new attribute yearFounded as a parameter in the child class’s __init__ function. Whenever you create a new attribute that is exclusive to the child class, you SHOULD include it as a parameter in the child class’s __init__ function. By doing so, any new attribute you created can be used as a parameter when creating an object of the child class.

  • You don’t absolutely need to include the new attribute(s) in the parameters of the child class’s __init__ function but if you don’t include them, you won’t be able to use the new attribute(s) when creating an object of the child class.

OK, but what if you also wanted to add a function exclusive to the child class? Let’s see how we can do that:

To add a function exclusive to the child class, simply create a new function in the body of the child class with self (or whatever you want to use in place of self) as the sole parameter. DO NOT place the new function in the body of the child class’s __init__ function!

As you can see here, the new function I added-teamDescription works perfectly with the child class BasketballTeam. However, watch what happens when I try to use the teamDescription function with an object of the parent class Team:

I can’t use the teamDescription function on the parent class Team because the teamDescription function is exclusive to the child class BasketballTeam; therefore, it can only be used by the child class.

Thanks for reading,

Michael

Python Lesson 13: Classes & Objects

Advertisements

Hello everybody,

It’s Michael, and today’s Python lesson will be on classes & objects in Python.

Python, like Java, is an object-oriented programming language. Everything in Python is an object, and each object in Python has its own attributes and methods (or functions in Python lingo). Classes in Python serve as object-builders (or blueprints for creating objects) just like classes in Java.

How do you create a class in Python? Let’s find out:

To create a class in Python, you simply need to use the keyword class. That’s it! No need to write public or private or anything like that in front of the class keyword like you would need to do in Java.

Alright, now let’s create an object of the class:

Creating an object of a Python class is similar to creating an object of a Java class, except in Java you would need the new keyword in front of the class name. Pretty simple right?

Now, I just demonstrated the simplest form of classes and objects. These examples wouldn’t serve you well when you’re working on any sort of Python programming project; classes and objects are more complex than what I just discussed.

To better understand classes and objects in Python, we need to understand the __init__ function. The __init__ function is built into every Python class, and it allows you to assign values to objects. Here’s an example of a class with the __init__ function:

In this class, the __init__ function has 4 parameters-self, year, month, and day. Year, month, and day are the variables for the RandomDate class.

There is also another parameter that I haven’t yet discussed-self. The self parameter refers to the class itself; it is used to access variables of the class, which in turn allows you to assign values to these variables. In the example above, I am able to access the year, month, and day variables by using self.year, self.month, and self.day, respectively.

  • Remember that in order to access the variables in the __init__ function, use this syntax: self.[variable name] = [variable name]
  • Remember that in order to access the variables in the __init__ function, use this syntax: self.[variable name] = [variable name]

You don’t absolutely have to call the first parameter self; you can name it whatever you want but it must be the first parameter of the function. Using the example above, let’s see what happens when we use another variable name instead of self:

This time, I replaced self with thedate but the code-block executed just fine since I remembered to use thedate as the first parameter.

Now, let’s add a method to class. Let’s also create a new object of the class and call the new method we created:

I added the function today to the RandomDate class and created a new object of the RandomDate class-r. The object r consists of the three main parameters of the RandomDate class-year, month, and day. The self (or thedate in this case) parameter isn’t included in the object creation, as it is only used to access the three main parameters.

Once I create the r object of the RandomDate class, I call the today function and get the output Today is September 20, 2020.

  • As you can see above, the three main parameters-2020, September, and 20-are all Strings. This is because you can only concatenate Strings with other Strings in Python. Just something to keep in mind when you’re writing your Python code.

Now that we have created an object of a class, let’s see how we can modify that object. First, let’s modify one of the properties of r:

In this example, I changed the value of day to 21 (in String format), called the today function again, and got the output Today is September 21, 2020.

Now, let’s say we wanted to get rid of the year. How do we do that? Take a look:

To delete an attribute from an object, follow this easy syntax: del [object name].[attribute to be deleted].

OK, so what if you wanted to get rid of the entire r object? This is what you would do:

To delete an entire object, just follow this very easy syntax: del [object name].

The last point I wanted to bring up regarding Python classes and objects is that, just like Python functions, they can’t be empty. However, the same empty-function workaround can be used for empty classes-simply using the keyword pass in the body of the function:

Thanks for reading,

Michael

Java Lesson 16: Abstract Classes

Advertisements

Hello everybody,

Michael here, and today’s post will be on abstract classes in Java.

First off, let’s start by discussing abstract classes. What is an abstract class? Well, let’s start off by explaining the concept of data abstraction. In Java (or any other programming language), data abstraction is the process of hiding certain details of the program and showing only essential information to the user. An abstract class is a restricted class that cannot be used to create objects-abstract classes can only be accessed if other classes inherit them (I’ll explain that more later). Also, just as regular classes can have regular methods, abstract classes can have abstract methods, which are methods that don’t have a body and can only be used in abstract classes.

  • It probably seems obvious to you guys, but the magic word  you would use to make a class or method abstract is abstract .
  • Abstract methods are created without a body, but the body of an abstract method is created in a subclass.

Alright, now that I’ve given you guys some explanation, let’s create an abstract class:

abstract class Abstract
{
public abstract void password();

public void username()
{
System.out.println(“MIKE2020”);
}
}

In this example, I created an abstract class with an abstract method-password-and a regular method-username(). Since abstract methods don’t have a body, the password() method doesn’t have a body either; the body of the password() method will be inherited from a subclass.

  • Also, I know it seems like a no-brainer, but abstract classes and methods would be denoted with the abstract key-word.

Another thing I wanted to note is that it’s not possible to create an object of an abstract class, since you can only access abstract classes by inheriting them from subclasses. Trying to create an object of an abstract class will generate an error, so statements like this aren’t possible in Java:

Abstract myObj = new Abstract();

But wait-I did say that you can access abstract classes and their methods by inheriting them from subclasses. Here’s how to do that:

class Login extends Abstract
{
@Override
public void password()
{
System.out.println(“abstract10n”);
}
}

In this example, I created a subclass of Abstract called Login (the fact that it’s a subclass is denoted by the extends key-word). Since Login is a subclass of Abstract, I was able to create the body of the password() method (which consists of a single System.out.println() command). Keep in mind that since Login isn’t an abstract class, password() isn’t an abstract method.

Now that we’ve got an abstract class and a subclass, what else do we need? We would need a main class to run the program. Here’s the main class:

public class Credentials
{
public static void main (String [] args)
{
Login login1 = new Login();
login1.username();
login1.password();
}
}

Here’s the output:

run:
MIKE2020
abstract10n
BUILD SUCCESSFUL (total time: 2 seconds)

In this example, I created the main class Credentials to run the program. To access the username() and password() methods, I had to create an object of the Login class, not the Abstract class, because I can only create objects of the subclass, not the abstract class. Also, I can only access the abstract class’s methods through the subclass, not through the abstract class itself.

Anyway, you might be wondering “What is the purpose of abstraction?”. The point of abstraction is that it improves the security of your program, as abstraction hides certain details of a program and only shows a program’s important details. Program details hidden in an abstract class are harder to access, as you would need to create a new subclass to access the abstract class and all of its methods.

Thanks for reading,

Michael

 

 

 

Java Lesson 3: User Input, Importing Classes, and Java Math

Advertisements

Hello everybody,

It’s Michael, and today’s post will be on user input, importing classes, and doing math in Java. I know these may seem like three totally unrelated topics, but I think they relate well to one another, which is why I’m going to cover all of them in this post.

First off, let’s discuss how to manage user input in your Java program. If you weren’t already aware, Java output doesn’t always have to be predefined-you can write your code so that you can choose the output.

The first thing you would need to do is import the Scanner class from Java, which is the class that handles all text input (don’t think about using it for graphics-heavy programs). Importing the Scanner class (or any class for that matter) allows you to use all its methods.

Here’s an example of a Scanner program:

The first thing I did was to import the Scanner class. I then created s, which is a variable of type Scanner. Remember to always create a Scanner variable every time you want to use the Scanner class in your program! And remember to ALWAYS set the parameters as (System.in).

I then used System.out.println to write the command asking the user for their input.  The user’s input then is stored in a variable, in this case int year. You must always store your input in a variable if you want it to display on the screen. What variable type you choose depends on what kind of input you are seeking. In this case, since I am seeking integers, I want to use type int. The value you assign to the variable would be (name of Scanner variable).next(type of variable your input is). Since my Scanner variable is named s and my input variable is of type int, the value I assigned my variable was s.nextInt(). The next______ method you use depends on the input variable’s type, so if I had a char variable I would use s.nextChar(). Please note that there is no nextString method so for String variables use next or nextLine.

For those who would like a video demonstration of the Scanner class, check out this program-Scanner demo.

Now, Scanner isn’t the only class you can import from Java. In fact there are plenty of other classes (and methods) you can use and import for a variety of purposes, such as the class Calendar for calendar programs. The best part is that you don’t need to memorize all of the classes available on Java, as there is a handy online dictionary where you can look up classes and methods that you need for your program. This dictionary does a very good job of explaining how you can use each available class.

Now at the beginning of this post, I said I was going to cover how to do math in Java. Well, there is a certain class that I will show you how to use to do just that-it’s the Math class. To access this class, use the line import java.lang.Math. Here are three programs utilizing the Math class and its methods.

This program asks the user for a negative number, then finds the absolute value of that number. Since I typed -33, the program calculated 33 as the absolute value.

This program asks the user for two numbers, then will calculate the value of the first number raised to the power of the second number. Since my first number was 9 and my second number was 3, the program printed out 729, or 9 cubed (which is a more colloquial way of saying “to the third power”)

This last program asks the user for a number, which in this context is an angle measurement for a right triangle. The program will then display the cosine (recall SOHCAHTOA) for that angle measurement; since I used a 49 degree angle in this example, the cosine is  0.3006 (rounded to four decimal places).

However, one thing to note is that the Math is more geared towards complex mathematical operations (like finding logs, trigonometric ratios, and square roots). You don’t need the Math class for basic arithmetic.

In case you’re wondering, here are two programs showing how to do basic arithmetic in Java:

This program demonstrates simple division; the user is asked for a number divisible by 3, then the program will print out the quotient of that number divided by 3. Since I used 612, the quotient displayed was 204.

This program utilizes the order of operations (think PEMDAS); the user is asked to type in a number and the program will print out the answer to the problem (pemdas/2)*3+8-4. Remember pemdas is the name of the variable where you will store the number you choose. I chose to store the user input as a double because I wanted a precise answer; had I stored the input as int , I would’ve gotten the nearest whole number (12) instead of the more precise answer I wanted-11.5.

  • Something I should have pointed out earlier-ALWAYS remember to put semicolons after each statement! To be clear, this only means the lines of code inside each method or class along with any import statements. This doesn’t mean semicolons are needed after class/method declarations themselves!
  • This isn’t totally necessary when coding, but the // symbol right before a line of code is a way to take notes within your program. The compiler won’t read any line of code that begins with //.

Now before I go, here’s a video demonstration on doing math in Java (both with the Math class and without)-Java Math.

Thanks for reading,

Michael