Java Video Tutorial 7

Java Video Tutorial 7In this part of my Java Video Tutorial I show you how to create classes in Java.

I cover Java fields (class variables) and methods (functions) first. I then explain what a private field is in detail. We then move on to what it means to overload a method, what a constructor is and how to overload a constructor.

Don’t worry. It sounds much more complicated than it is. You should however check out the previous tutorials before you try to learn this stuff here Java Video Tutorial.

If you like videos like this share it

Code From the Video

// Basic class definition
// public means this class can be used by other classes
// Class names should begin with a capital letter
// A file can't contain two public classes. It can contain classes that are not public
// If you place class files in the same folder the java compiler will be able to find them

public class Monster{
	
	// Class Variables or Fields
	// You declare constants with final
	
	public final String TOMBSTONE = "Here Lies a Dead monster";
	
	// private fields are not visible outside of the class
	private int health = 500;
	private int attack = 20;
	private int movement = 2;
	private int xPosition = 0;
	private int yPosition = 0;
	private boolean alive = true;
	
	// public variables are visible outside of the class
	// You should have as few as possible public fields
	public String name = "Big Monster";
	
	// Class Methods
	// Accessor Methods are used to get and set the values of private fields
	
	public int getAttack()
	{
		return attack;
	}
	
	public int getMovement()
	{
		return movement;
	}
	
	public int getHealth()
	{
		return health;
	}
	
	// You can create multiple versions using the same method name
	// Now setHealth can except an attack that contains decimals
	// When overloading a method you can't just change the return type
	// Focus on creating methods that except different parameters
	
	public void setHealth(int decreaseHealth)
	{
		health = health - decreaseHealth;
		if (health < 0)
		{
			alive = false;
		}
	}
	
	public void setHealth(double decreaseHealth)
	{
		int intDecreaseHealth = (int) decreaseHealth;
		health = health - intDecreaseHealth;
		if (health < 0)
		{
			alive = false;
		}
	}
	
	/* The Constructor
	 * Code that is executed when an object is created from this class definition
	 * The method name is the same as the class
	 * The constructor is only executed once per object
	 * The constructor can't return a value
	 */
	
	public Monster(int health, int attack, int movement)
	{
		this.health = health;
		this.attack = attack;
		this.movement = movement;
		/* If the attributes had the same names as the class health, attack, movement
		 * You could refer to the objects fields by proceeding them with this
		 * this.health = health;
		 * this.attack = attack;
		 * objectFieldName = attributeFieldName;
		 */
		
	}
	
	// You can overload constructors like any other method
	// The following constructor is the one provided by default if you don't create any other constructors
	// Default Constructor
	
	public Monster()
	{
		
	}
	
	/* You can use the this keyword to call other constructors
	 * public LessonSeven(int newHealth)
	 * {
	 * 		health = newHealth;
	 * }
	 * 
	 * public LessonSeven(int newHealth, int newAttack)
	 * {
	 * 		this(newHealth); // Any calls to another constructor must occur on the first line
	 * 		attack = newAttack;
	 * }
	 */
	
}

public class JavaLessonSeven {
	
	public static void main(String[] args){
		
		// You create an object using the blueprint of this class as follows
		// className objectName = new className();
		
		Monster Frank = new Monster();
		
		// Since the objects name is public you can change it directly
		
		Frank.name = "Frank";
		
		// You retrieve class field values by listing the objectName.fieldName
		// You execute class methods by listing objectName.methodName()
		
		System.out.println(Frank.name + " has an attack value of " + Frank.getAttack());
	
	}
}

31 Responses to “Java Video Tutorial 7”

  1. Madhusha Mendis says:

    Great video series for java ,Thank You Very Much sir for this videos,I’ve learnt java accurately by your video series.

  2. lucky says:

    hi,this was so helpful…

    but i have problem with the ” passing arrays to methods” concept.Here is the code which i tried .
    hope u will reply soon

    import java.util.*;
    import java.io.*;
    class Arr
    {
    int r,c;
    int arr[][];

    Arr(int r,int c)
    {
    this.r=r;
    this.c=c;
    arr=new int[r][c];
    }
    int[][] getMatrix() throws IOException
    {
    Scanner s=new Scanner(System.in);
    for(int i=0;i<r;i++)
    {

    for(int j=0;i<c;j++)
    arr[i][j]=s.nextInt();

    }
    return arr;

    }
    int[][] sum(int a[][],int b[][])
    {
    int q[][] =new int[r][c];
    for(int i=0;i<r;i++)
    {
    for(int j=0;j<c;j++)
    {

    q[i][j]=a[i][j]+b[i][j];
    }
    }return q;
    }

    void displayMatrix(int k[][])
    {
    for(int i=0;i<r;i++)
    {
    for(int j=0;j<c;j++)
    {
    System.out.println("the resultant matrix is:"+k[i][j]);
    }

    }

    }
    }
    public class To
    {
    Scanner sc=new Scanner(System.in);
    public static void main(String[] args) throws IOException
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("enter no of rows:");
    int r=sc.nextInt();
    System.out.println("enter no of columns:");
    int c=sc.nextInt();

    Arr a=new Arr(r,c);
    Arr b=new Arr(r,c);

    int x[][],y[][],z[][];
    System.out.println("enter matrix a:");
    x=a.getMatrix();
    System.out.println("enter matrix b:");
    y=b.getMatrix();

    z=a.sum(x, y);

    b.displayMatrix(z);

    }
    }

  3. Carlos says:

    Is there something special that needs to be done to get this to work on NetBeans?

    Great vids by the way.

    Thanks

    • admin says:

      Thank you very much 🙂 No everything should work on NetBeans without an issue. On occasion I import a library, but aside from that everything should work perfectly

  4. LisaT says:

    Class variables/fields are different than private fields? I’m trying to make this work in my brain. All monsters will have a TOMBSTONE I follow that. Then you have the health, attack, movement, x and y position and alive boolean listed next as private fields. Why are they not also final? If the word private means they are treated that way then why not privatize the TOMBSTONE? I think I’m stuck on the difference between each and all. All monsters will have a TOMBSTONE when they die but each monster has health… is that the difference?

    • Derek Banas says:

      I grew to dislike the idea behind this game after I made it. I mainly focus on giving examples of all the different ways you can use the different tools in Java. I think this pseudo game just got in the way. Feel free to ignore that part of the videos because I very quickly get off this topic and move into better videos very soon. I’m sorry if it was confusing

  5. John says:

    Hey Derek just wanna say thank you for taking the time to make the vids, i am currently doing programming at university and i am having a lot of trouble understanding the methods and the classes, no matter how many times i watch them i cannot get my head around the idea. What your doing there in the monster game i been trying to follow along by programming as well but there is a lot of stuff i don’t get, if you dont mind clearing some of the things up can you please add me on skype trujohn3665 thx

    • Derek Banas says:

      The easiest way to send me questions is actually through my website, or through YouTube. I check YouTube instant messages normally every 2 hours. I will gladly answer any questions you’d like. I have tried chatting and it normally doesn’t work for some reason. Just make a list of questions and I’ll answer them

  6. Allan says:

    Hi Derek,
    I really love your videos. I first came across your videos while doing python. Your python videos are fantastic. I have an exam next week on java so I’m watching your videos day and night. I’m having a problem understanding the toString method. Can you give me some advice.

    • Derek Banas says:

      Every class you create is of type object. So, every class you create comes with the toString method by default. When your code tries to print an object it will print to screen whatever you define in toString. So, by defining it you can decide what prints out. Does that help?

      • Allan says:

        Firstly, thanks for your reply. You have given me some hope. I understand somewhat but can you give me a bit of code showing how it is used. I don’t quite understand the syntax. Thanks again.

        • Derek Banas says:

          You’re very welcome 🙂 Sorry, but I’m not sure what code you are looking for. I get tons of questions and I forget past conversations some time. Sorry about that

          • Allan says:

            Hi again Derek,
            Right now you are my lifeline for passing my exam on Friday. I’m trying to figure out how to print the values in an array using the toString method. I welcome any suggestions or comments.

            Thanks(an avid fan)
            Allan.

            • Derek Banas says:

              Hi, Create a toString method in a java class and override the default. The array would be part of that class. Use a for loop to iterate and return the results in toString. I hope that helps 🙂

  7. Adamwpe says:

    Why can’t public String access the private int (attack) but in public void you can?

  8. Mike says:

    Hi,

    I appreciate the work you do here. I am learning, slowly but surely. One thing I applaud you greatly is the fact that you take time and respond to the questions and comments. I admire you for that. Thanks for your effort!

  9. Mike says:

    by the way, which is this your website or do you have another website? Just want to know where you prefer to be contacted for questions or comments.

  10. average_guy says:

    I just wanted to say that you are doing an AMAZING job,your youtube channel is the best channel I’ve ever seen.

  11. Duteee says:

    Hi Derek on line 70 where it says the method has the same name as the class, is that supposed to say the constructor has the same name as the class????

  12. Afan says:

    there is a mistake in the youtube video. at 7:10

    the paramater in the video is written as the follow.
    public void setHealth(double decrease)
    instead of
    public void setHealth(double decreaseHealth)

Leave a Reply

Your email address will not be published.

Google+