The questions are : why can a method of this SetSyle class be called without ins
ID: 3727148 • Letter: T
Question
The questions are :
why can a method of this SetSyle class be called without instantiating the object
why doesn't the object have to be instantiated?
class SetStyle
{
//
//
public static void setHeaderColor()
{
Console.ForegroundColor = ConsoleColor.Green;
}
public static void setErrorColor()
{
Console.ForegroundColor = ConsoleColor.Red;
}
public static void setDefaultColor()
{
Console.ForegroundColor = ConsoleColor.White;
}
}
Here's how to call a properly declared method of a class without instantiating the object.
SetStyle.setHeaderColor();
Explanation / Answer
public class SetStyle
{
// in Object oriented paradigm non-static methods are called the instance methods. they are the behaviour of an object which invoke with the help of object of its class. Static method belongs to the class rather than an object of that class.
// In this current given SetStyle class, the defined static methods are not using any instance variables.
// Here the static methods are not depending on instance creating hence they are the properties of the SetStyle class.
//Static methods can not be overriden.Here the given static methods will never be changed or overriden.
//Here the current SetStyle class is having its own methods like setHeaderColor, setErrorColor and setDefaultColor.
// These methods are not related to the object of this class. These methods can shared by all the instance methods of this class.
//The static methods and static variables will be initialized first, before initializing any instance variables or methods.
public static void setHeaderColor()
{
Console.ForegroundColor = ConsoleColor.Green;
}
public static void setErrorColor()
{
Console.ForegroundColor = ConsoleColor.Red;
}
public static void setDefaultColor()
{
Console.ForegroundColor = ConsoleColor.White;
}
public static void main(String args[])
{
// with out creating object we can access the static methods
// This is the syntax to access the static methods by using class name.
SetStyle.setDefaultColor();
SetStyle.setHeaderColor();
SetStyle.setErrorColor();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.